• Home
  • Tools
    • Color Chart
  • Software
    • Windows tricks
      • Windows 11 Speed Up Tricks
      • Windows Command Prompt CMD
    • Android Phone
      • Android – Dangerous Settings to Turn Off
    • Projects
      • Copy Files
      • Php Autoscript
      • Web Tools
  • Payments
  • Notes
  • System Tips

Notes

ACCESS 2022 | Browsers | Css | Htacess | Html | Html5 | Javascript | Microsoft Excel | Mysql | Mysql Dumps | Php | Vb.net | VBscript | Windows <=8 | Windows >=10 | WP | WP Plugin | WP Themes | _Misc Software |

ABCDEFGHIJKLMNOPQRSTUVWXYZ
ON
PRT
OFF

<- Look Inside Data
Conditions:
Order:
1|2|3|4|5|6|7|8|
50 Language Operation Title
Keywords
Application
Code Languageid
Show Html
Show Iframe
Make Public
Viewed
Viewed Date
Php Formatting Html_entity_decode
decode format
Restoring Html Saves
Php



2
09/09/2023
Php Formatting Htmlentities
html convert format
Html, Php Saves
Php



2
09/09/2023
Php Formatting Remove Ascii > 127
ascii remove delete
String Cleanup
Php



0
03/07/2024
Php Function Create Graphic Button On The Fly
grapic button image color
session_start();
session_register('sessioncode');
//Header("Content-type: image/jpeg");
//echo "beg test";
$filename = "images/image1.gif";
$im = imagecreate(55, 15);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 100, 100, 100);
imagecolortransparent($im, $bg);
//imagestring($im, 5, 0, 0, substr(strtoupper(md5("Myshit".$sessioncode)), 0,6), $textcolor);
imagestring($im, 5, 0, 0, substr(strtoupper("Myshit"), 0,6), $textcolor);
imageGif($im,$filename);
ImageDestroy($im);
//***************************************************************
$filename = "images/image.gif";
$img = ImageCreate(200,20);
$red = ImageColorAllocate($img, 255, 0, 0); $white = ImageColorAllocate($img, 255, 255, 255);
ImageString($img, 3, 3, 3, "Uh, this is an image!", $white); ImageGif($img, $filename);

ImageDestroy($img);
echo "";
echo "Finished";
exit();
?>
Php



1235
09/09/2023
Php Function Automatically Make Urls Clickable
hyperlinks click email url link
function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];

if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from URL
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
//return $matches[1] . "$url" . $ret;
return $matches[1] . "$url" . $ret;
}

function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;

if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from URL
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "$dest" . $ret;
}

function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "$email";
}

function MakeHyperlink($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);

// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret);
$ret = trim($ret);
return $ret;
}
Php



1617
09/09/2023
Php Function Ziping And Unziping Server Folders Using Php
zip unzip directory folder backup mysql backup directory
// I use a browser script that send the proper data to back up since if have multiple accounts. I separate the small files in one zip and large files in another. Under case 1. you will notice mp3 and zip this prevents bloated zips which may fail. Video and music should be done seperately from the rest of the files. I included a mysql backup that gets the data and makes a .sql file if you give it database information.

class Utils
{
public static function listDirectory($dir)
{
$result = array();
$root = scandir($dir);
foreach($root as $value) {
if($value === '.' || $value === '..') {
continue;
}
if(is_file("$dir$value")) {
$result[] = "$dir$value";
continue;
}
if(is_dir("$dir$value")) {
$result[] = "$dir$value/";
}
foreach(self::listDirectory("$dir$value/") as $value)
{
$result[] = $value;
}
}
return $result;
}
}

/*
use if you need to rename or auto download
$file = '/path/to/zip/file.zip';
$file_name = basename($file);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . $file_name);
header("Content-Length: " . filesize($file));
readfile($file);
exit;
*/


$project=$_GET["pr"];$projectid=$_GET["id"];$PHPfolder=$_GET["fo"];$PHPdatabase=$_GET["db"];$user=$_GET["us"]; $password=$_GET["pa"];$return1=$_GET["re"];
$exportstring="pr=$project&fo=$PHPfolder&db=$PHPdatabase&us=$user&pa=$password&re=$return1&id=$projectid";
$server="localhost";
$AC=$_GET["L"];
$topDir=dirname(__FILE__);
$folder0="/".$PHPfolder;
$source_dir = $topDir.$folder0."/";
if(strlen($PHPfolder)==1)$source_dir = $topDir."/"; // For those sites where zipdemo is in their root
if(is_dir($topDir."/BACKED")==false){ mkdir($topDir."/BACKED", 0777); }
if($AC=="" && strlen($PHPdatabase)>1){
mysql_connect($server,$user,$password);
mysql_select_db($PHPdatabase);
$backupFile =$source_dir.$PHPdatabase.".sql";
$result .= "# MySQL Data Backup of ".$PHPdatabase."\n";
$result .= "# This was generated on " . date("m/d/Y") . "\n\n";

$tables = mysql_list_tables($PHPdatabase);
for($i = 0; $i < mysql_num_rows($tables); $i++){
$table = mysql_tablename ($tables, $i);
if(substr($table,0,7)!="tblStat"){
$result .= "# Start of $table \n";
$result .= "TRUNCATE TABLE $table;\n";
$query = mysql_query("select * from $table");
$num_fields = mysql_num_fields($query);
$result .= "$table fields (\n";
for($ii = 0; $ii < $num_fields; $ii++) {
$result.= mysql_field_name($query,$ii)."-".mysql_field_type($query,$ii)."(".mysql_field_len($query,$ii).")".mysql_field_flags($query,$ii)."\n";
}
$result.=");\n";
$numrow = mysql_num_rows($query);

while( $row = mysql_fetch_array($query, MYSQL_NUM))
{
$result .= "INSERT INTO ".$table." VALUES(";
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
$row[$j] = str_replace("\r","",$row[$j]);
if (isset($row[$j]))
$result .= "\"$row[$j]\"";
else
$result .= "\"\"";
if ($j<($num_fields-1))
$result .= ", ";
}
$result .= ");\n";
}
}
if ($i+1 != mysql_num_rows($tables))
$result .= "\n";
}
$ID++;

// ===================

$fp = fopen($backupFile, "w");
fwrite($fp, $result);
// Move to the start of the file
fclose($fp);
}
//echo $topDir."/BACKED".$folder0."L.zip"; echo $exportstring;exit;
switch($AC){
case 1:
$zip_file = $topDir."/BACKED/".$project."L.zip";
$fi0=$_GET["fi0"];
$exportstring.="&fi0=$fi0&fi1=/BACKED/".$project."L.zip";
break;
default:
$zip_file = $topDir."/BACKED/".$project.".zip";
$exportstring.="&fi0=/BACKED/".$project.".zip";
break;
}
//echo $zip_file;exit;
$file_list = Utils::listDirectory($source_dir);
//echo "shit2";exit;
$zip = new ZipArchive();
if ($zip->open($zip_file, ZIPARCHIVE::CREATE) === true) {
foreach ($file_list as $file) {
if ($file !== $zip_file) {
switch($AC){
case 1:
if(filesize($file)>= 250000 && strpos($file,".zip")==0 && strpos($file,".mp3")==0) $zip->addFile($file, substr($file, strlen($source_dir)));
break;
default:
if(filesize($file)<= 250000) $zip->addFile($file, substr($file, strlen($source_dir)));
break;
}
}
//$i++;if($i==10)break;
}
$zip->close();
}
if($AC==""){ header("location:zipdemo.php?$exportstring&L=1");exit; }
else{ header("location:http://$return1?$exportstring"); exit; }
?>

This script includes header files which may hiccup if error reporting is set to show warnings. The one below will handle warnings.

class Utils
{
public static function listDirectory($dir)
{
$result = array();
$root = scandir($dir);
foreach($root as $value) {
if($value === '.' || $value === '..') {
continue;
}
if(is_file("$dir$value")) {
$result[] = "$dir$value";
continue;
}
if(is_dir("$dir$value")) {
$result[] = "$dir$value/";
}
foreach(self::listDirectory("$dir$value/") as $value)
{
$result[] = $value;
}
}
return $result;
}
}

/*
$file = '/path/to/zip/file.zip';
$file_name = basename($file);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=" . $file_name);
header("Content-Length: " . filesize($file));
readfile($file);
exit;
*/
$project=$_GET["pr"];$projectid=$_GET["id"];$PHPfolder=$_GET["fo"];$PHPdatabase=$_GET["db"];$user=$_GET["us"]; $password=$_GET["pa"];$return1=$_GET["re"];
$project="Peak_Wellness";$PHPdatabase="the1324812461410";$user="the1324812461410";$password="v4K#htNPNfeG";
$return1="www.softwarewebdesign.com/SWD/EMAIL/backmeup.php";$projectid=27;
$exportstring="pr=$project&fo=$PHPfolder&db=$PHPdatabase&us=$user&pa=$password&re=$return1&id=$projectid";
$server="the1324812461410.db.11744884.hostedresource.com";
$AC=$_GET["L"];
$topDir=dirname(__FILE__);
$folder0="/".$PHPfolder;
$source_dir = $topDir."/"; //.$folder0."/";
if(is_dir($topDir."/BACKED")==false){ mkdir($topDir."/BACKED", 0777); }
if($AC=="" && strlen($PHPdatabase)>1){
mysql_connect($server,$user,$password);
mysql_select_db($PHPdatabase);
$backupFile =$source_dir.$PHPdatabase.".sql";
$result .= "# MySQL Data Backup of ".$PHPdatabase."\n";
$result .= "# This was generated on " . date("m/d/Y") . "\n\n";

$tables = mysql_list_tables($PHPdatabase);
for($i = 0; $i < mysql_num_rows($tables); $i++){
$table = mysql_tablename ($tables, $i);
if(substr($table,0,7)!="tblStat"){
$result .= "# Start of $table \n";
$result .= "TRUNCATE TABLE $table;\n";
$query = mysql_query("select * from $table");
$num_fields = mysql_num_fields($query);
$result .= "$table fields (\n";
for($ii = 0; $ii < $num_fields; $ii++) {
$result.= mysql_field_name($query,$ii)."-".mysql_field_type($query,$ii)."(".mysql_field_len($query,$ii).")".mysql_field_flags($query,$ii)."\n";
}
$result.=");\n";
$numrow = mysql_num_rows($query);

while( $row = mysql_fetch_array($query, MYSQL_NUM))
{
$result .= "INSERT INTO ".$table." VALUES(";
for($j=0; $j<$num_fields; $j++)
{
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace("\n","\\n",$row[$j]);
$row[$j] = str_replace("\r","",$row[$j]);
if (isset($row[$j]))
$result .= "\"$row[$j]\"";
else
$result .= "\"\"";
if ($j<($num_fields-1))
$result .= ", ";
}
$result .= ");\n";
}
}
if ($i+1 != mysql_num_rows($tables))
$result .= "\n";
}
$ID++;

// ===================

$fp = fopen($backupFile, "w");
fwrite($fp, $result);
// Move to the start of the file
fclose($fp);
}
//echo "Done sql";exit;
//echo $topDir."/BACKED".$folder0."L.zip"; echo $exportstring;exit;
switch($AC){
case 1:
$zip_file = $topDir."/BACKED/".$project."L.zip";
$fi0=$_GET["fi0"];
$exportstring.="&fi0=$fi0&fi1=/BACKED/".$project."L.zip";
break;
default:
$zip_file = $topDir."/BACKED/".$project.".zip";
$exportstring.="&fi0=/BACKED/".$project.".zip";
break;
}
//echo $zip_file;exit;
$file_list = Utils::listDirectory($source_dir);
//echo "shit2";exit;
$zip = new ZipArchive();
if ($zip->open($zip_file, ZIPARCHIVE::CREATE) === true) {
foreach ($file_list as $file) {
if ($file !== $zip_file) {
switch($AC){
case 1:
if(filesize($file)>= 250000 && strpos($file,".zip")==0 && strpos($file,".mp3")==0) $zip->addFile($file, substr($file, strlen($source_dir)));
break;
default:
if(filesize($file)<= 250000) $zip->addFile($file, substr($file, strlen($source_dir)));
break;
}
}
//$i++;if($i==10)break;
}
$zip->close();
}
/*
if($AC==""){ header("location:zipdemo.php?$exportstring&L=1");exit; }
else{ header("location:http://$return1?$exportstring"); exit; }
*/
if($AC==""){ echo "Continue"; exit; }
else{ echo "Continue"; exit; }

?>

To unzip an archive just upload the archive and this script into the directory and run. Do this for both zips to get the complete archive.

UNZIP SCRIPT

$topDir=dirname(__FILE__)."/";
//echo $topDir;exit;
$zip = new ZipArchive;
if ($zip->open('SUBWAYL.zip') === TRUE) {
$zip->extractTo($topDir);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
Php



1767
09/09/2023
Php Function Quick Debug Routine
debug
Php



1
03/01/2024
Php Function Preg_match Is The Ereg Replacement
ereg eregi preg_match preg match
preg_match() Would be the pcre equivalent. The patterns will pretty much be the same, only real difference is that the preg_xxx functions require an opening/closing delimiter in the pattern and modifiers (if needed) are specified after the closing delimiter.

So for instance:
ereg(".",$var1)
would be
preg_match("~.~",$var1) // ~ is used as the pattern delimiter.
or for instance,


eregi(".",$var1) // case in-sensitive
would be
preg_match("~.~i",$var1) // i modifier added to make it case in-sensitive

if(eregi("color",$fieldName))

preg_match("~color~i",$fieldName))
Php



1253
09/09/2023
Php Function String
Length ord sub
Php



2
09/09/2023
Php Function Choosing What Errors To See
error reporting
Developer
php_flag display_startup_errors on

.htacess
php_flag display_errors on

/ Turn off all error reporting
error_reporting(0);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL)
Php



2
09/09/2023
Php Function Get Current Directory Name And Path In PHP
working directory path file
Directory
Use the getcwd() Function to Get the Current Directory Name in PHP
Use the dirname() Function to Get the Current Directory Name in PHP
Use the basename() Function to Get the Current Directory Name in PHP

Use the getcwd() Function to Get the Current Directory Name in PHP
The getcwd() function gives the current working directory. The returned value is a string on success.

The function does not take any parameters. The function returns false in case of failure.

Letโ€™s consider the following directory structure.

??? var
? ??? www
? ??? html
| ???project
| ???index.php
The PHP file lies inside the project directory. The getcwd() function will return the name of the current working directory, which is project.

We can use the echo function to display the content of the function. We can see in the output section that the getcwd() function returns the current working directory with its path.

echo getcwd();
Output:

/var/www/html/project
Use the dirname() Function to Get the Current Directory Name in PHP
We can also use the dirname() function to get the current directory name in PHP. The function returns the path of the parent directory.

It accepts two parameters where the first one is the path and the second one is levels. Levels indicate the number of directories to move up.

Finally, we can use the __FILE__ magic constants in the dirname() function to get the name of the current directory. The __FILE__ constant returns the full path of the current file along with the file name.

We can demonstrate these constants and the function in the above directory structure. For example, we get the following result when we echo the __FILE__ constant from the index.php file.

echo __FILE__;
Output:

/var/www/html/project/index.php
For example, write the dirname() function in the index.php file with the __FILE__ constant as the parameter.

echo dirname(__FILE__);
$topDir=dirname(__FILE__);
Output:

/var/www/html/project
In this way, we can get the current working directory name in PHP.

Use the basename() Function to Get the Current Directory Name in PHP
We can use the basename() function to get the current working directory name without the path in PHP. We can apply this function with the result of the above two functions.

The basename() function returns the name of the base file or folder from the given path. For example, if the path provided is /var/www/html/project, the output will be project.

For example, use the functions dirname(__FILE__) and getcwd() as the parameters for the basename() function. In this way, we can get the current working directory name in PHP.

echo basename(dirname(__FILE__))."
";
echo basename(getcwd())."n";
Output:
Php



2
09/09/2023
Php Function Protecting Passwords
Encrypt Decrypt security password
Security Code App
Php



3
02/22/2024
Php Function SESSION VARIABLES NOT WORKING
DEBUG $_SESSION
HEMPDBASE
Php



0
03/02/2024
Php Function Create Lionks Backup
links $PDS_
Developer
Php



0
08/21/2024
Php Function Deletefile.php
delete exist file
Backup File Info
Php



0
05/18/2025
Php Ini Php Ini Partial
ini
Filter List Textarea
disable_functions no value no value
display_errors Off Off
display_startup_errors Off Off
doc_root no value no value
docref_ext no value no value
docref_root no value no value
enable_dl Off Off
enable_post_data_reading On On
error_append_string no value no value
error_log error_log error_log
error_prepend_string no value no value
error_reporting 22519 22519
expose_php Off Off
extension_dir /opt/cpanel/ea-php80/root/usr/lib64/php/modules /opt/cpanel/ea-php80/root/usr/lib64/php/modules
file_uploads On On
hard_timeout 2 2
highlight.comment #FF8000 #FF8000
highlight.default #0000BB #0000BB
highlight.html #000000 #000000
highlight.keyword #007700 #007700
highlight.string #DD0000 #DD0000
html_errors On On
ignore_repeated_errors Off Off
ignore_repeated_source Off Off
ignore_user_abort Off Off
implicit_flush Off Off
include_path .:/opt/cpanel/ea-php80/root/usr/share/pear .:/opt/cpanel/ea-php80/root/usr/share/pear
input_encoding no value no value
internal_encoding no value no value
log_errors On On
log_errors_max_len 1024 1024
mail.add_x_header On On
mail.force_extra_parameters no value no value
mail.log no value no value
max_execution_time 60 60
max_file_uploads 20 20
max_input_nesting_level 64 64
max_input_time 60 60
max_input_vars 1000 1000
max_multipart_body_parts -1 -1
memory_limit 512M 512M
open_basedir no value no value
output_buffering no value no value
output_encoding no value no value
output_handler no value no value
post_max_size 516M 516M
precision 14 14
Php



0
12/08/2025
Php Language Number Type
integer
Php



2
09/09/2023
Php Language HtmlEntities ,html_entity_decode
html convert formatt
You could use htmlspecialchars and htmlspecialchars_decode combined with htmlEntities ,html_entity_decode

htmlspecialchars โ€” Convert special characters to HTML entities

See documentation here http://php.net/htmlspecialchars

htmlspecialchars_decode โ€” Convert special HTML entities back to characters
See documentation here http://php.net/manual/en/function.htmlspecialchars-decode.php

$htmlcode = htmlentities(htmlspecialchars(thehmldata));
echo $htmlcode;

echo html_entity_decode(htmlspecialchars_decode($htmlcode)
Php



2
09/09/2023
Php Language Empty
strip tag
Developer
Php



2
09/09/2023
Php Language PHP Language
random
Php



0
12/17/2024
Php Language Finds The Position Of The Last Occurrence Of A String
search find
Developer
PHP strrpos() Function

Example
Find the position of the last occurrence of "php" inside the string:

echo strrpos("I love php, I love php too!","php");
?>
Definition and Usage
The strrpos() function finds the position of the last occurrence of a string inside another string.

Note: The strrpos() function is case-sensitive.

Related functions:

strpos() - Finds the position of the first occurrence of a string inside another string (case-sensitive)
stripos() - Finds the position of the first occurrence of a string inside another string (case-insensitive)
strripos() - Finds the position of the last occurrence of a string inside another string (case-insensitive)
Syntax
Php



0
02/13/2025
Php Language Loops In Php
loops do while
Php
Php



0
10/14/2024
Php Network Doing Email In Php
email
Send Emails
$notify=false;$subject="Subject Here."; $body="$Body Here ".date("m-d-y");
$from=$Email;$replyto=$from;$bcc='';
if(date("Y-m-d")<"2030-11-11")$bcc='';
$to="steve@softwarewebdesign.com";
$headers = "MIME-Version: 1.0rn";
$headers .= "Content-type: text/html; charset=iso-8859-1rn";
$headers .= "From: ".$from."rn";
$headers .= "Reply-To: ".$replyto."rn";
if($bcc!='')$headers .= "bcc:$bccrn";
mail($to, $subject, $body, $headers);
Php



1
02/23/2026
Php Object USING IMAGES
image resize function getimagesize
Images
Php



5
09/09/2023
Php Object Determin A Files Type
file type
Checking Files
if looking for images
The following constants are defined, and represent possible exif_imagetype() return values:

Imagetype Constants
Value Constant
1 IMAGETYPE_GIF
2 IMAGETYPE_JPEG
3 IMAGETYPE_PNG
4 IMAGETYPE_SWF
5 IMAGETYPE_PSD
6 IMAGETYPE_BMP
7 IMAGETYPE_TIFF_II (intel byte order)
8 IMAGETYPE_TIFF_MM (motorola byte order)
9 IMAGETYPE_JPC
10 IMAGETYPE_JP2
11 IMAGETYPE_JPX
12 IMAGETYPE_JB2
13 IMAGETYPE_SWC
14 IMAGETYPE_IFF
15 IMAGETYPE_WBMP
16 IMAGETYPE_XBM
17 IMAGETYPE_ICO
18 IMAGETYPE_WEBP
19 IMAGETYPE_AVIF
Note:

exif_imagetype() will emit an E_NOTICE and return false if it is unable to read enough bytes from the file to determine the image type.



In PHP, you can determine the file type of a movie, PDF, or image using several functions. mime_content_type() returns the MIME type, finfo provides more detailed information, and exif_imagetype() is specifically for images.
Detailed Explanation:

1. mime_content_type():
This function uses the magic.mime file to return the MIME type of a file. For example:

mime_content_type('movie.mp4') might return video/mp4.

mime_content_type('document.pdf') might return application/pdf.
mime_content_type('image.jpg') might return image/jpeg.

2. finfo:
This function provides more detailed information about a file, including its type. It can be used to check for specific file types or extensions.
3. exif_imagetype():
This function is specifically designed for images. It reads the first few bytes of an image file to determine its type. It can be used to verify that a file is actually an image before processing it further.

Example:
Code

// Check file type using mime_content_type()
$file = 'movie.mp4';
$mime_type = mime_content_type($file);

if ($mime_type == 'video/mp4') {
echo "The file is a video.";
} elseif ($mime_type == 'application/pdf') {
echo "The file is a PDF.";
} elseif (strpos($mime_type, 'image/') !== false) { // Check if MIME type starts with 'image/'
echo "The file is an image.";
} else {
echo "The file type is unknown.";
}

// Check file type using finfo (more robust)
$finfo = finfo_open(FILEINFO_MIME_TYPE); // Open a fileinfo handle
$mime_type = finfo_file($finfo, $file, FILEINFO_MIME_TYPE);
finfo_close($finfo);

if ($mime_type == 'video/mp4') {
echo "The file is a video (finfo).";
} elseif ($mime_type == 'application/pdf') {
echo "The file is a PDF (finfo).";
} elseif (strpos($mime_type, 'image/') !== false) {
echo "The file is an image (finfo).";
} else {
echo "The file type is unknown (finfo).";
}

// Check image type using exif_imagetype()
$file = 'image.jpg';
$image_type = exif_imagetype($file);

if ($image_type == IMAGETYPE_JPEG) {
echo "The file is a JPEG image.";
} elseif ($image_type == IMAGETYPE_PNG) {
echo "The file is a PNG image.";
} elseif ($image_type == IMAGETYPE_GIF) {
echo "The file is a GIF image.";
} else {
echo "The file is not a supported image type.";
}

?>

Key Considerations:

Security:
.

Always validate file types on the server-side to prevent malicious files from being uploaded.
MIME Type vs. File Extension:
.
File extensions can be easily spoofed, so relying solely on them is not secure. MIME types provide a more reliable indication of file content.
finfo for Detailed Information:
.
finfo can be used to check for specific file types or extensions, providing more flexibility than mime_content_type().
exif_imagetype() for Image Validation:
.
This function is specifically designed for images and can be used to verify that a file is actually an image before processing it.
Php



0
05/18/2025
Php Server Get Information About Your User
page refer php self
My current page is: $PHP_SELF

$ref=$_SERVER['HTTP_REFERER']; page they came from

$ip=$_SERVER['REMOTE_ADDR']; get their ipaddress

echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";

$browser = get_browser(null, true);
print_r($browser);
?>
The above example will output something similar to:


Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040803 Firefox/0.9.3

Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[css] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
Php



1500
09/09/2023
Php Server Get Ipaddress
ipaddress
Reading Serve Ip
To read your
server's internal IP address in PHP, you should use the $_SERVER['SERVER_ADDR'] superglobal. For the server's external (public) IP address, the most reliable way is to query an external service.
Internal Server IP Address
The $_SERVER superglobal array contains various server and request-related information. The SERVER_ADDR key typically holds the IP address of the host server running the script.
php

$server_ip = $_SERVER['SERVER_ADDR'];
echo "Server Internal IP Address: " . $server_ip;
?>

Note: This may return 127.0.0.1 (localhost) in some configurations or if running from a command line interface (CLI).
External Server IP Address
To get the IP address that your server uses to communicate with the internet (its public IP), you generally need to make a request to an external service that simply echoes back the IP address it sees.
A common and reliable method is to use Amazon's check IP service via file_get_contents() or curl.
php

// Use file_get_contents to fetch the IP from a reliable external service
$external_ip = file_get_contents('https://checkip.amazonaws.com');

// Filter and validate the IP address before use
if (filter_var($external_ip, FILTER_VALIDATE_IP) !== false) {
echo "Server External IP Address: " . trim($external_ip);
} else {
echo "Could not retrieve external IP address.";
}
?>

Alternative Methods

Using DNS: If your server has a domain name, you can use PHP's gethostbyname() function to find the IP associated with that hostname.
php

$domain_name = 'yourdomain.com';
$ip_from_dns = gethostbyname($domain_name);
echo "IP from DNS lookup: " . $ip_from_dns;
?>

Using Sockets (Linux/Unix): A more robust dynamic method, especially useful in CLI environments, involves connecting to a public DNS server (like Google's 8.8.8.8) to determine the outgoing interface IP address.
php

$sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
socket_connect($sock, '8.8.8.8', 53);
socket_getsockname($sock, $addr);
socket_close($sock);
echo "Server Outgoing IP: " . $addr;
?>




$ip=$_SERVER['REMOTE_ADDR'];

if($_SERVER['REMOTE_ADDR']=="208.73.252.147"){

function get_ip() {
if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
//check ip from share internet
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
//to check ip is pass from proxy
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
Php



1190
09/09/2023
Php Server Server Information - Using The $_SERVER
server information function
URL INFO [USE parse_url under langueage

'PHP_SELF'
The filename of the currently executing script, relative to the document root. For instance, $_SERVER['PHP_SELF'] in a script at the address http://example.com/test.php/foo.bar would be /test.php/foo.bar. The __FILE__ constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name since PHP 4.3.0. Previously it was not available.
'argv'
Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string.
'argc'
Contains the number of command line parameters passed to the script (if run on the command line).
'GATEWAY_INTERFACE'
What revision of the CGI specification the server is using; i.e. 'CGI/1.1'.
'SERVER_ADDR'
The IP address of the server under which the current script is executing.

'SERVER_NAME'
The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_SOFTWARE'
Server identification string, given in the headers when responding to requests.
'SERVER_PROTOCOL'
Name and revision of the information protocol via which the page was requested; i.e. 'HTTP/1.0';
'REQUEST_METHOD'
Which request method was used to access the page; i.e. 'GET', 'HEAD', 'POST', 'PUT'.

Note:

PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was HEAD.

'REQUEST_TIME'
The timestamp of the start of the request. Available since PHP 5.1.0.
'REQUEST_TIME_FLOAT'
The timestamp of the start of the request, with microsecond precision. Available since PHP 5.4.0.
'QUERY_STRING'
The query string, if any, via which the page was accessed.
'DOCUMENT_ROOT'
The document root directory under which the current script is executing, as defined in the server's configuration file.
'HTTP_ACCEPT'
Contents of the Accept: header from the current request, if there is one.
'HTTP_ACCEPT_CHARSET'
Contents of the Accept-Charset: header from the current request, if there is one. Example: 'iso-8859-1,*,utf-8'.
'HTTP_ACCEPT_ENCODING'
Contents of the Accept-Encoding: header from the current request, if there is one. Example: 'gzip'.
'HTTP_ACCEPT_LANGUAGE'
Contents of the Accept-Language: header from the current request, if there is one. Example: 'en'.
'HTTP_CONNECTION'
Contents of the Connection: header from the current request, if there is one. Example: 'Keep-Alive'.
'HTTP_HOST'
Contents of the Host: header from the current request, if there is one.
'HTTP_REFERER'
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
'HTTP_USER_AGENT'
Contents of the User-Agent: header from the current request, if there is one. This is a string denoting the user agent being which is accessing the page. A typical example is: Mozilla/4.5 [en] (X11; U; Linux 2.2.9 i586). Among other things, you can use this value with get_browser() to tailor your page's output to the capabilities of the user agent.

'HTTPS'
if ($_SERVER["HTTPS"] == "on") {$pageURL .= "s";}
Set to a non-empty value if the script was queried through the HTTPS protocol.

Note: Note that when using ISAPI with IIS, the value will be off if the request was not made through the HTTPS protocol.

'REMOTE_ADDR'
The IP address from which the user is viewing the current page.
if($_SERVER['REMOTE_ADDR']=="127.0.0.1"){ $server='localhost';$user='greatone';$password='gr38t0n3';$database='angel'; $_SESSION['LEVEL']=10;}
else{ $server="localhost";$user="angelde_flunky1";$password="wied55";$database="angelde_a1"; }

'REMOTE_HOST'
The Host name from which the user is viewing the current page. The reverse dns lookup is based off the REMOTE_ADDR of the user.

Note: Your web server must be configured to create this variable. For example in Apache you'll need HostnameLookups On inside httpd.conf for it to exist. See also gethostbyaddr().

'REMOTE_PORT'
The port being used on the user's machine to communicate with the web server.
'REMOTE_USER'
The authenticated user.
'REDIRECT_REMOTE_USER'
The authenticated user if the request is internally redirected.
'SCRIPT_FILENAME'

The absolute pathname of the currently executing script.

Note:

If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $_SERVER['SCRIPT_FILENAME'] will contain the relative path specified by the user.

'SERVER_ADMIN'
The value given to the SERVER_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host.
'SERVER_PORT'
The port on the server machine being used by the web server for communication. For default setups, this will be '80'; using SSL, for instance, will change this to whatever your defined secure HTTP port is.
'SERVER_SIGNATURE'
String containing the server version and virtual host name which are added to server-generated pages, if enabled.
'PATH_TRANSLATED'
Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping.

Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache. This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO.

'SCRIPT_NAME'
Contains the current script's path. This is useful for pages which need to point to themselves. The __FILE__ constant contains the full path and filename of the current (i.e. included) file.
'REQUEST_URI'
The URI which was given in order to access this page; for instance, '/index.html'.
'PHP_AUTH_DIGEST'
When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation).
'PHP_AUTH_USER'
When doing HTTP authentication this variable is set to the username provided by the user.
'PHP_AUTH_PW'
When doing HTTP authentication this variable is set to the password provided by the user.
'AUTH_TYPE'
When doing HTTP authenticated this variable is set to the authentication type.
'PATH_INFO'
Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URL http://www.example.com/php/path_info.php/some/stuff?foo=bar, then $_SERVER['PATH_INFO'] would contain /some/stuff.
'ORIG_PATH_INFO'
Original version of 'PATH_INFO' before processed by PHP.
Php



1006
09/09/2023
Php String Manipulate Strings
find replace first caps upper case lower case section substring date
Php



1396
10/21/2025
Php Variables Using Arrays
array
Php



2
09/09/2023
Php Variables Cookies
cookies json_encode store arrays post get session
Storing Settings
To delete a cookie in PHP, you must use the
setcookie() function with an expiration time in the past. This tells the user's browser to remove the cookie.
Steps to Delete a PHP Cookie

Ensure no output is sent to the browser before calling setcookie(), as it modifies HTTP headers.
Call the setcookie() function with the same name and parameters (path, domain, etc.) that were used when the cookie was created.
Set the expiration time to a time in the past, for example, an hour ago (time() - 3600). The value of the cookie can be set to an empty string.

Example Code
php

// Set a cookie (example, expires in 30 days)
$cookie_name = "username";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day

// ... your other code ...

// To delete the cookie named "username":
// Set the expiration date to one hour ago (or any time in the past)
setcookie("username", "", time() - 3600, "/");
setcookie("humans_21909", "", time() - 3600, "/");

// Optionally, you can also unset the cookie from the current script's $_COOKIE superglobal array
unset($_COOKIE['username']);

echo "Cookie 'username' has been deleted.";




This example stores my variables into cookies and retrieves them back when I want them:

$appid="635667735729502691";$appidLast="";
if($_GET["BACK"]==1) {
$savedSessions=array();$savedRequests=array();
$savedSessions= json_decode($_COOKIE["SESSIONARRAY".$appid]); $savedPosts= json_decode($_COOKIE["POSTARRAY".$appid]); $savedGets= json_decode($_COOKIE["GETARRAY".$appid]);
foreach($savedSessions as $k=>$value) {
$_SESSION[$k]=$value;
}
foreach($savedPosts as $k=>$value) {
$_POST[$k]=$value;
}
foreach($savedGets as $k=>$value) {
$_GET[$k]=$value;
}
} //CHECK CURRENT APPLICATION
else{
$json = json_encode($_SESSION, true);setcookie('SESSIONARRAY'.$appid,$json, time()+1800,"/");
$json = json_encode($_POST, true);setcookie('POSTARRAY'.$appid,$json,time()+1800,"/");
$json = json_encode($_GET, true);setcookie('GETARRAY'.$appid,$json,time()+1800,"/");
}
Php



837
09/09/2023
Vb.net Archive Email Remove Sub
email move
Outlook Mail Cleaner
Vb.net



7
02/26/2026
Vb.net Controls Combo Box Control
combo value archive example
Vb.net



4
07/27/2025
Vb.net Controls How To Use MSGBOX YES NO
message box
Decision
vate Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim payed As Integer
Dim balance As Integer
Dim paying As Integer
Dim d As Integer
Dim c As Integer
Try

Dim ans As Integer
If TextBox7.Text = "" Or 0 Then

MsgBox("please enter amount", MsgBoxStyle.Critical)
Else
If TextBox6.Text = 0 Then

MsgBox("the student is fully payed", MsgBoxStyle.Critical)
Else
ans = MsgBox(" are you want to upadate the students payment? ", MsgBoxStyle.YesNo, "confirm ")
If MsgBoxResult.Yes Then


payed = Val(TextBox5.Text)
balance = Val(TextBox6.Text)
paying = Val(TextBox7.Text)
d = payed + paying
c = balance - paying
TextBox5.Text = d
TextBox6.Text = c

Dim SqlQuery = "UPDATE sample SET [Payed Amount] ='" & TextBox5.Text & "',Balance ='" & TextBox6.Text & "' WHERE ID = " & a & " ; "
Dim sqlcommand As New OleDbCommand
With sqlcommand
.CommandText = SqlQuery
.Connection = conn
.ExecuteNonQuery()
End With
MsgBox("student payment succesfully updated")
My.Computer.Audio.Play(My.Resources.CASHREG, AudioPlayMode.Background)
If TextBox6.Text = 0 Then
MsgBox("the student is now fully paid", MsgBoxStyle.Information)
TextBox7.Text = ""
Else

MsgBox("students current balance is " & Convert.ToString(TextBox6.Text))
LoadListView()
TextBox7.Text = ""
End If
Else
Exit Sub
End If
End If
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
Vb.net



0
12/11/2023
Vb.net Controls DoEvents In .NET
doevents
Developer
18

Application.DoEvents()
Vb.net



0
12/14/2023
Vb.net Controls Simple Drag Drop Example
drag drop mousedown
Developer
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Populate the ListBox with file paths
ListBox1.Items.Add("C:examplefile1.txt")
ListBox1.Items.Add("C:examplefile2.txt")
ListBox1.Items.Add("C:examplefile3.txt")

' Enable drag-and-drop functionality
ListBox1.AllowDrop = False
End Sub

Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Check if an item is selected
If ListBox1.SelectedItem IsNot Nothing Then
' Get the selected file path
Dim filePath As String = ListBox1.SelectedItem.ToString()

' Ensure the file exists before attempting to drag
If IO.File.Exists(filePath) Then
' Start the drag-and-drop operation
Dim files() As String = {filePath}
Dim dataObject As New DataObject(DataFormats.FileDrop, files)
ListBox1.DoDragDrop(dataObject, DragDropEffects.Copy)
End If
End If
End Sub
End Class
Key Points:
File Paths in ListBox: The ListBox should contain valid file paths that exist on the system.
Drag-and-Drop Operation: The DoDragDrop method is used to initiate the drag-and-drop operation, passing the file paths as a DataObject with the DataFormats.FileDrop format.
MouseDown Event: The drag operation starts when the user clicks and holds the mouse button on a selected item.
How It Works:
When the user clicks on an item in the ListBox and drags it, the application checks if the item is a valid file path.
If valid, the file path is passed to the DoDragDrop method, allowing the user to drop the file into File Explorer or other compatible applications.
This approach ensures a smooth drag-and-drop experience while maintaining proper validation of file paths.



I just dragged a file from my application to File Explorer using this code:
VB.NET:
Imports System.Collections.Specialized
Private Sub Form1_MouseDown(sender As Object, e As MouseEventArgs) Handles Me.MouseDown
Dim data As New DataObject()
Dim filePaths As New StringCollection

filePaths.Add(Path.Combine(Application.StartupPath, "TestData.txt"))
data.SetFileDropList(filePaths)
DoDragDrop(data, DragDropEffects.Copy)
End Sub
If you are doing drag and drop just within your application then you can use whatever you want as that first argument to DoDragDrop and look for that same type when dropping. If you're doing it between applications then you do as I have here, i.e. create a DataObject, add data to it in the appropriate format(s) and then pass that to DoDragDrop. That will ensure that any application that supports drag and drop between applications will be able to access that data in the appropriate standard format.

That DataObject class also has SetText, SetImage and SetAudio methods for specific data types and a SetData method for everything else. They are the complementary methods to the e.Data.GetX methods you call in a DragDrop event handler.
Why is my data not saved to my database?



Certainly! If you want to drag items from a ListBox in VB.NET and treat them as files rather than strings, you can achieve this by handling the DragDrop and DragEnter events. Below is an example of how you can implement this:

Step-by-Step Implementation
Set up the ListBox for Drag-and-Drop:

Enable drag-and-drop for the ListBox.
Handle the MouseDown event to initiate the drag operation.
Handle DragEnter and DragDrop Events:

Ensure the target control accepts the dragged data.
Handle the drop operation to process the files.
Example Code

Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Enable drag-and-drop for the ListBox
ListBox1.AllowDrop = True

' Add some items to the ListBox
ListBox1.Items.Add("C:pathtofile1.txt")
ListBox1.Items.Add("C:pathtofile2.txt")
End Sub

Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
If ListBox1.SelectedItem IsNot Nothing Then
' Start the drag-and-drop operation with the selected item as a file
ListBox1.DoDragDrop(New DataObject(DataFormats.FileDrop, New String() {ListBox1.SelectedItem.ToString()}), DragDropEffects.Copy)
End If
End Sub

Private Sub ListBox1_DragEnter(sender As Object, e As DragEventArgs) Handles ListBox1.DragEnter
' Check if the data being dragged is a file
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
e.Effect = DragDropEffects.Copy
Else
e.Effect = DragDropEffects.None
End If
End Sub

Private Sub ListBox1_DragDrop(sender As Object, e As DragEventArgs) Handles ListBox1.DragDrop
' Handle the drop operation
If e.Data.GetDataPresent(DataFormats.FileDrop) Then
Dim files As String() = CType(e.Data.GetData(DataFormats.FileDrop), String())
For Each file As String In files
ListBox1.Items.Add(file)
Next
End If
End Sub
End Class
Explanation
Form Load Event:

Enables drag-and-drop for the ListBox.
Adds some initial file paths to the ListBox.
MouseDown Event:

Initiates the drag-and-drop operation when an item is selected and the mouse button is pressed.
DragEnter Event:

Checks if the data being dragged is a file and sets the appropriate effect.
DragDrop Event:

Handles the drop operation by adding the dropped files to the ListBox.
This code allows you to drag items from the ListBox and treat them as files, making it easier to integrate with other file-based operations. If you have any further questions or need additional customization, feel free to ask!

Example One Drag And Drop Controls Using Vb.Net
2.Drag and Drop operation-simple example
2.1. Basic drag & drop operation example
Let's look at some examples, starting with simple drag and drop operation. Create a Visual Basic. net windows application and design a form with control & Drag Drop event procedure as follows

To enable drag & drop for text

1. Place two textboxes and set Allowdrop property of a second textbox to true.
2. Add the following code

Private MouseIsDown As Boolean = False 'variable declaration

Private Sub TextBox1_MouseDown(ByVal sender As Object, ByVal e As _

System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseDown

'Set a flag to show that the mouse is down.

MouseIsDown = True

End Sub

Private Sub TextBox1_MouseMove(ByVal sender As Object, ByVal e As _

System.Windows.Forms.MouseEventArgs) Handles TextBox1.MouseMove

If MouseIsDown Then

' Initiate dragging.

TextBox1.DoDragDrop(TextBox1.Text,DragDropEffects.Copy)

End If

MouseIsDown = False

End Sub

Private Sub TextBox2_DragEnter(ByVal sender As Object, ByVal e As _

System.Windows.Forms.DragEventArgs) Handles TextBox2.DragEnter

'Check the format of the data being dropped.

If (e.Data.GetDataPresent(DataFormats.Text)) Then

' Display the copy cursor.

e.Effect = DragDropEffects.Copy

Else

' Display the no-drop cursor.

e.Effect = DragDropEffects.None

End If

End Sub

Private Sub TextBox2_DragDrop(ByVal sender As Object, ByVal e As _

System.Windows.Forms.DragEventArgs) Handles TextBox2.DragDrop

'Paste the text.

TextBox2.Text = e.Data.GetData(DataFormats.Text)

End Sub
In the above example, the MouseDown event is used to set a flag showing that the mouse is down, and then the DoDragDrop method is called in the MouseMove event. Although you could initiate the drag in the MouseDown event, doing so would create undesirable behavior: Every time a user clicks the control, the no-drag cursor would be displayed.

T
Vb.net



4
05/25/2025
Vb.net Customizing How To: Rename A File In Visual Basic
rename file
You don't need to mention the complete file path in newFileName parameter, just mention new file name here otherwise you will get ArgumentException.

Dim filePath As String = "C:fingerprint1"

If File.Exists(filePath) Then

Dim strNewFileName As String = "Fingerprint221"

My.Computer.FileSystem.RenameFile(filePath, strNewFileName)

End If
See also
Use the RenameFile method of the My.Computer.FileSystem object to rename a file by supplying the current location, file name, and the new file name. This method cannot be used to move a file; use the MoveFile method to move and rename the file.

To rename a file
Use the My.Computer.FileSystem.RenameFile method to rename a file. This example renames the file named Test.txt to SecondTest.txt.

VB

Copy
' Change "c:test.txt" to the path and filename for the file that
' you want to rename.
My.Computer.FileSystem.RenameFile("C:Test.txt", "SecondTest.txt")
This code example is also available as an IntelliSense code snippet. In the code snippet picker, the snippet is located in File system - Processing Drives, Folders, and Files. For more information, see Code Snippets.
Vb.net



0
12/09/2023
Vb.net Customizing Code Behinnd MR Button Webtools
chr MR
Web Tools
? seperates values
chr(032032?chr(032 use ascii
"bof" BEGIN OF FILE
"eof" END OF FILE
"lf" remove double CrLf
"td" Replace tabs with dash
"ts" tab to spaces
"tc" tab to comma
"lfc" replace line feeds with commas
"lb-" Replace line breaks with -
"{GET}" EXTRACT BETWEEN { }
"{DEL}" 'Delete BETWEEN { }
Vb.net



0
11/29/2024
Vb.net Customizing Running A 3rd Party Application
computer name shell write
3rd Party Software
ou should consider using Process.Start instead of Shell, as Shell is a holdover from the VB 6 days and Process.Start is built into the .NET Framework.

Here is an example of running Microsoft Word via the command line, passing it parameters, including file name and any flags:

Sub Main()
OpenMicrosoftWord("C:UsersSamDocumentsOfficeGears.docx")
End Sub

'''
''' Open the path parameter with Microsoft Word.
'''

Private Sub OpenMicrosoftWord(ByVal f As String)
Dim startInfo As New ProcessStartInfo
startInfo.FileName = "WINWORD.EXE"
startInfo.Arguments = f
Process.Start(startInfo)
End Sub
==============================
old school
Dim R As String = My.Computer.Name '
R = GetIni("Database", R, INI)
If R = "" Then
WriteIni("Database", My.Computer.Name, "Dropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb", INI)
Shell("write.exe " + INI, vbNormalFocus) : Exit Sub
End If
Vb.net



2
07/27/2025
Vb.net Customizing Close Running Processes
application close running
Windows

VB.Net Close window by title



Top Answer

Answered Jun 29, 2012 ยท 6 votes

Try using something like this. using Process.MainWindowTitle


to get the Title Text and Process.CloseMainWindow


to close down the UI, its a little more graceful than killing the Process.

Note: Contains does a case-sensitive search

Imports System.Diagnostics
Module Module1
Sub Main()
Dim myProcesses() As Process = Process.GetProcesses
For Each p As Process In myProcesses
If p.MainWindowTitle.Contains("Notepad") Then
p.CloseMainWindow()
End If
Next
End Sub
End Module

Display processes running


Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click
File1.Items.Clear()
For Each p In Process.GetProcesses
If p.MainWindowTitle <> "" Then
'File1.Items.Add(p.MainWindowTitle + "..running")
File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]")
End If
Next
End Sub
Vb.net



1
07/21/2025
Vb.net Customizing Debug Properties Of Project
signing compile debug settings
Vb 22
under the menu "debug" look for "xxxx debug properties"

Application
compile
debug
references
resources
services
Settings
signing
my extension's
security
publish
code analysis.
Vb.net



0
02/05/2025
Vb.net Customizing Handling Directories
directory
Developer

Creating Directories


If Not System.IO.Directory.Exists(YourPath) Then
System.IO.Directory.CreateDirectory(YourPath)
End If
Vb.net



0
03/23/2025
Vb.net Customizing Move Emails From Multiple Accounts To An Outlook Data File
multiple accounts move email flag
OUTLOOK
Imports Microsoft.Office.Interop.Outlook

Module Module1
Sub Main()
' Initialize Outlook application
Dim outlookApp As New Application()
Dim namespaceMAPI As [NameSpace] = outlookApp.GetNamespace("MAPI")

' Specify the path to the Outlook Data File (PST)
Dim pstFilePath As String = "C:PathToYourDataFile.pst"
Dim pstDisplayName As String = "Archived Emails"

' Add the PST file to Outlook if not already added
Try
namespaceMAPI.AddStore(pstFilePath)
Catch ex As Exception
Console.WriteLine("PST file already added or an error occurred: " & ex.Message)
End Try

' Get the root folder of the PST file
Dim pstRootFolder As MAPIFolder = namespaceMAPI.Folders(pstDisplayName)

' Loop through all accounts in Outlook
For Each account As Account In namespaceMAPI.Accounts
Console.WriteLine("Processing account: " & account.DisplayName)

' Access the Inbox folder of the account
Dim inboxFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox")

' Create a subfolder in the PST file for this account
Dim accountFolder As MAPIFolder = pstRootFolder.Folders.Add(account.DisplayName)

' Move emails from the Inbox to the PST subfolder
For i As Integer = inboxFolder.Items.Count To 1 Step -1
Try
Dim mailItem As MailItem = TryCast(inboxFolder.Items(i), MailItem)
If mailItem IsNot Nothing Then
mailItem.Move(accountFolder)
Console.WriteLine("Moved email: " & mailItem.Subject)
End If
Catch ex As Exception
Console.WriteLine("Error moving email: " & ex.Message)
End Try
Next
Next

Console.WriteLine("Emails moved successfully!")
End Sub
End Module
Key Points:
Add Reference: Add a reference to the Microsoft.Office.Interop.Outlook library in your project.
PST File Path: Replace "C:PathToYourDataFile.pst" with the actual path to your PST file.
Permissions: Ensure you have the necessary permissions to access the accounts and move emails.
Error Handling: The code includes basic error handling, but you may need to enhance it for production use.
Outlook Version: This code is compatible with Outlook versions that support the Interop library.
Notes:
Running this code may require administrative privileges.
Ensure Outlook is properly configured and running on the machine.
Test the script in a safe environment before using it on live data to avoid accidental data loss.

=============== option =================

' Initialize Outlook application
Dim outlookApp As New Outlook.Application()
Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI")

' Loop through all accounts
For Each account As Outlook.Account In namespaceMAPI.Accounts
MsgBox(account.DisplayName)
'Console.WriteLine($"Processing account: {account.DisplayName}")

' Access the Inbox folder for the account
Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox")

' Specify the target folder (e.g., "Processed Emails")
'Dim targetFolder As MAPIFolder = namespaceMAPI.Folders(account.DisplayName).Folders("Processed Emails")


Next

'Console.WriteLine("Emails moved successfully!")

======= flag status ==================

Determining if an email is "flagged" in VB.NET typically refers to checking the follow-up flag status of an email within an application like Microsoft Outlook. This involves interacting with the Outlook object model.
Here's a general approach using the Outlook Object Model in VB.NET:

Reference the Outlook Library: In your VB.NET project, add a reference to the Microsoft Outlook Object Library.
Create an Outlook Application Object:

Code

Dim olApp As New Outlook.Application()

Get the Namespace and Folder.
Code

Dim olNS As Outlook.Namespace = olApp.GetNamespace("MAPI")
Dim inboxFolder As Outlook.MAPIFolder = olNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

Iterate Through Mail Items.
Code

For Each item As Object In inboxFolder.Items
If TypeOf item Is Outlook.MailItem Then
Dim mailItem As Outlook.MailItem = CType(item, Outlook.MailItem)

' Check the FlagStatus property
If mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagged Then
' The email is flagged
Console.WriteLine($"Email: {mailItem.Subject} is flagged.")
ElseIf mailItem.FlagStatus = Outlook.OlFlagStatus.olFlagComplete Then
' The email flag is marked complete
Console.WriteLine($"Email: {mailItem.Subject} flag is complete.")
Else
' The email is not flagged
Console.WriteLine($"Email: {mailItem.Subject} is not flagged.")
End If
End If
Next

Explanation:

Outlook.OlFlagStatus.olFlagged: Indicates the email has been flagged for follow-up.
Outlook.OlFlagStatus.olFlagComplete: Indicates the follow-up flag has been marked as complete.
Outlook.OlFlagStatus.olNotFlagged: Indicates no follow-up flag is set.

Important Considerations:

Outlook Installation:
This approach requires Microsoft Outlook to be installed on the machine where the VB.NET application is running.
Security Prompts:
Outlook may display security prompts when your application attempts to access its data.
Error Handling:
Implement robust error handling to manage potential issues like Outlook not being open or access denied.
Alternatives:
For scenarios where Outlook isn't installed or direct interaction is not desired, consider using APIs like Microsoft Graph API (if working with Outlook 365) to access mailbox data and flag status.
Vb.net



3
08/02/2025
Vb.net Customizing Control Window State Of App
maximize all programs minimize
Outlook Mail Cleaner
automatically minimize a window in VB.NET, you can set the WindowState property of the form to FormWindowState.Minimized. This can be done in various scenarios, such as when the form loads, in response to a user action (like clicking a button), or based on a timer.
1. Minimizing the Current Form:
To minimize the form where the code is executed:
Code

Me.WindowState = FormWindowState.Minimized
This line of code can be placed within an event handler, such as a button click event or a form load event.
2. Minimizing All Active Forms:
To minimize all forms currently open in your application:
Code

For Each frm As Form In Application.OpenForms
frm.WindowState = FormWindowState.Minimized
Next frm
This code iterates through the Application.OpenForms collection and sets the WindowState of each form to Minimized.
3. Minimizing an External Application Window (Advanced):
Minimizing an external application's window requires using Windows API functions. This involves obtaining the window handle of the target application and then using functions like ShowWindow to manipulate its state. This is a more complex approach and typically involves PInvoke to call unmanaged code.
Example for a specific event:
To minimize the form when a specific button is clicked:
Code

Private Sub btnMinimize_Click(sender As Object, e As EventArgs) Handles btnMinimize.Click
Me.WindowState = FormWindowState.Minimized
End Sub

Maximize all apps


Imports System.Runtime.InteropServices
Module ModConnection

' Import the ShowWindow function from user32.dll

Public Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
End Function

' Constants for ShowWindow

Public Const SW_SHOWNORMAL = 1
Public Const SW_SHOWMAXIMIZED = 3
Public Const SW_SHOWMINIMIZED = 6

your function calls

Private Sub btProcess_Click(sender As Object, e As EventArgs) Handles btProcess.Click

File1.Items.Clear()
For Each p In Process.GetProcesses
If p.MainWindowTitle <> "" Then
'File1.Items.Add(p.MainWindowTitle + "..running")
File1.Items.Add("[" + p.ProcessName + "=" + p.MainWindowTitle + "]")
ShowWindow(p.MainWindowHandle, SW_SHOWMAXIMIZED)
End If
Next
End Sub
Vb.net



0
10/19/2025
Vb.net Customizing Control Top Left Width & Height Of Form
form top left width height
Form Size
Public Sub New()
' Set form title
Me.Text = "Form Position and Size Example"

' Set form position (Top, Left) and size (Width, Height)
Me.StartPosition = FormStartPosition.Manual ' Required to manually set position
Me.Left = 200 ' Distance from left edge of screen
Me.Top = 150 ' Distance from top edge of screen
Me.Width = 800 ' Form width in pixels
Me.Height = 600 ' Form height in pixels

' Add a button to display current values
Dim btnShowInfo As New Button()
btnShowInfo.Text = "Show Form Info"
btnShowInfo.Dock = DockStyle.Fill
AddHandler btnShowInfo.Click, AddressOf ShowFormInfo
Me.Controls.Add(btnShowInfo)
End Sub

Private Sub ShowFormInfo(sender As Object, e As EventArgs)
' Display current position and size
MessageBox.Show(
$"Top: {Me.Top}" & vbCrLf &
$"Left: {Me.Left}" & vbCrLf &
$"Width: {Me.Width}" & vbCrLf &
$"Height: {Me.Height}",
"Form Info"
)
End Sub


Public Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New MainForm())
End Sub
End Class



MsgBox(My.Computer.Screen.WorkingArea.Height)
MsgBox(My.Computer.Screen.WorkingArea.Width)
MessageBox.Show(
$"Top: {Me.Top}" & vbCrLf &
$"Left: {Me.Left}" & vbCrLf &
$"Width: {Me.Width}" & vbCrLf &
$"Height: {Me.Height}",
"Form Info"
)
Vb.net



1
11/17/2025
Vb.net Customizing Line Numbers On A Rich Textbox
line number textbox
Textbox
Imports System.Drawing
Imports System.Windows.Forms

Public Class Form1
Inherits Form

Private WithEvents rtb As New RichTextBox()
Private WithEvents pnlLineNumbers As New Panel()

Public Sub New()
' Form setup
Me.Text = "RichTextBox with Line Numbers"
Me.Size = New Size(800, 600)

' Panel for line numbers
pnlLineNumbers.Dock = DockStyle.Left
pnlLineNumbers.Width = 50
pnlLineNumbers.BackColor = Color.LightGray
AddHandler pnlLineNumbers.Paint, AddressOf pnlLineNumbers_Paint

' RichTextBox setup
rtb.Dock = DockStyle.Fill
rtb.Font = New Font("Consolas", 10)
rtb.WordWrap = False
rtb.ScrollBars = RichTextBoxScrollBars.ForcedBoth

' Add controls
Me.Controls.Add(rtb)
Me.Controls.Add(pnlLineNumbers)
End Sub

' Redraw line numbers when text changes or scrolls
Private Sub rtb_TextChanged(sender As Object, e As EventArgs) Handles rtb.TextChanged
pnlLineNumbers.Invalidate()
End Sub

Private Sub rtb_VScroll(sender As Object, e As EventArgs) Handles rtb.VScroll
pnlLineNumbers.Invalidate()
End Sub

' Draw line numbers
Private Sub pnlLineNumbers_Paint(sender As Object, e As PaintEventArgs)
e.Graphics.Clear(pnlLineNumbers.BackColor)

Dim firstIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, 0))
Dim firstLine As Integer = rtb.GetLineFromCharIndex(firstIndex)

Dim lastIndex As Integer = rtb.GetCharIndexFromPosition(New Point(0, rtb.Height))
Dim lastLine As Integer = rtb.GetLineFromCharIndex(lastIndex)

Dim lineHeight As Integer = TextRenderer.MeasureText("A", rtb.Font).Height

Dim y As Integer = 0
For i As Integer = firstLine To lastLine
Dim lineNumber As String = (i + 1).ToString()
Dim size As Size = TextRenderer.MeasureText(lineNumber, rtb.Font)
e.Graphics.DrawString(lineNumber, rtb.Font, Brushes.Black,
pnlLineNumbers.Width - size.Width - 5, y)
y += lineHeight
Next
End Sub

' Entry point

Public Shared Sub Main()
Application.EnableVisualStyles()
Application.Run(New Form1())
End Sub
End Class
Vb.net



1
12/08/2025
Vb.net Database Create Read Only Recordset
create recordset error list box
LISTBOX
Vb.net



2
09/09/2023
Vb.net Database Delete A Record From A DAO Recordset
delete recordset
Vb.net



0
10/09/2022
Vb.net Database Extract Data From A Record In A DAO Recordset
extreact recordset
Vb.net



2
09/09/2023
Vb.net Database Using The Datagridview Control
datagrid access mdb view
access developer
Vb.net



4
02/06/2025

Software Web Design