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 | ABCDEFGHIJKLMNOPQRSTUVWXYZONPRTOFF codeid operationid title keywords application code languageid show_html show_iframe make_public viewed viewed_date language operation <- Look Inside DataConditions: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 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) html_entity_decode โ Convert HTML entities to their corresponding characters Description ยถ html_entity_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null): string html_entity_decode() is the opposite of htmlentities() in that it converts HTML entities in the string to their corresponding characters. More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type โ i.e., for XML, this function does not decode named entities that might be defined in some DTD โ and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is. Parameters ยถ string The input string. flags A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#xFFFD; (otherwise) instead of returning an empty string. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. encoding An optional argument defining the encoding used when converting characters. If omitted, encoding defaults to the value of the default_charset configuration option. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. Return Values ยถ Returns the decoded string. Changelog ยถ Version Description 8.1.0 flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. 8.0.0 encoding is nullable now. Examples ยถ Example #1 Decoding HTML entities <?php $orig = "I'll "walk" the <b>dog</b> now"; $a = htmlentities($orig); $b = html_entity_decode($a); echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now echo $b; // I'll "walk" the <b>dog</b> now ?> Notes ยถ Php 2 09/09/2023 Php Formatting Htmlentities html convert format Html, Php Saves (PHP 4, PHP 5, PHP 7, PHP 8) htmlentities โ Convert all applicable characters to HTML entities Description ยถ htmlentities( string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null, bool $double_encode = true ): string This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. The get_html_translation_table() function can be used to return the translation table used dependent upon the provided flags constants. If you want to decode instead (the reverse) you can use html_entity_decode(). Parameters ยถ string The input string. flags A bitmask of one or more of the following flags, which specify how to handle quotes, invalid code unit sequences and the used document type. The default is ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. Available flags constants Constant Name Description ENT_COMPAT Will convert double-quotes and leave single-quotes alone. ENT_QUOTES Will convert both double and single quotes. ENT_NOQUOTES Will leave both double and single quotes unconverted. ENT_IGNORE Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it ยป may have security implications. ENT_SUBSTITUTE Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of returning an empty string. ENT_DISALLOWED Replace invalid code points for the given document type with a Unicode Replacement Character U+FFFD (UTF-8) or &#FFFD; (otherwise) instead of leaving them as is. This may be useful, for instance, to ensure the well-formedness of XML documents with embedded external content. ENT_HTML401 Handle code as HTML 4.01. ENT_XML1 Handle code as XML 1. ENT_XHTML Handle code as XHTML. ENT_HTML5 Handle code as HTML 5. encoding An optional argument defining the encoding used when converting characters. If omitted, encoding defaults to the value of the default_charset configuration option. Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the default_charset configuration option may be set incorrectly for the given input. The following character sets are supported: Supported charsets Charset Aliases Description ISO-8859-1 ISO8859-1 Western European, Latin-1. ISO-8859-5 ISO8859-5 Little used cyrillic charset (Latin/Cyrillic). ISO-8859-15 ISO8859-15 Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). UTF-8 ASCII compatible multi-byte 8-bit Unicode. cp866 ibm866, 866 DOS-specific Cyrillic charset. cp1251 Windows-1251, win-1251, 1251 Windows-specific Cyrillic charset. cp1252 Windows-1252, 1252 Windows specific charset for Western European. KOI8-R koi8-ru, koi8r Russian. BIG5 950 Traditional Chinese, mainly used in Taiwan. GB2312 936 Simplified Chinese, national standard character set. BIG5-HKSCS Big5 with Hong Kong extensions, Traditional Chinese. Shift_JIS SJIS, SJIS-win, cp932, 932 Japanese EUC-JP EUCJP, eucJP-win Japanese MacRoman Charset that was used by Mac OS. '' An empty string activates detection from script encoding (Zend multibyte), default_charset and current locale (see nl_langinfo() and setlocale()), in this order. Not recommended. Note: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted. double_encode When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything. Return Values ยถ Returns the encoded string. If the input string contains an invalid code unit sequence within the given encoding an empty string will be returned, unless either the ENT_IGNORE or ENT_SUBSTITUTE flags are set. Changelog ยถ Version Description 8.1.0 flags changed from ENT_COMPAT to ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401. 8.0.0 encoding is nullable now. Examples ยถ Example #1 A htmlentities() example <?php $str = "A 'quote' is <b>bold</b>"; // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str); // Outputs: A 'quote' is <b>bold</b> echo htmlentities($str, ENT_QUOTES); ?> Example #2 Usage of ENT_IGNORE <?php $str = "x8F!!!"; // Outputs an empty string echo htmlentities($str, ENT_QUOTES, "UTF-8"); // Outputs "!!!" echo htmlentities($str, ENT_QUOTES | ENT_IGNORE, "UTF-8"); ?> See Also ยถ html_entity_decode() - Convert HTML entities to their corresponding characters get_html_translation_table() - Returns the translation table used by htmlspecialchars and htmlentities htmlspecialchars() - Convert special characters to HTML entities nl2br() - Inserts HTML line breaks before all newlines in a string urlencode() - URL-encodes string 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 function ec($vari,$sect){ return "Section ".$sect." -- ".$vari.""; } $debug.=ec($_SESSION["FIELDSAVE1"],154); //line 154 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 ____String length____strlen($val) ___String to ascii code____ord($val) $newstring=substr($val,25,1);$acii=ord($newstring); The 160 is a space problem for browsers ____section of string____substr($val,start,extract#of char) $newstring=substr($teaser,5,1); start at char 5 and remove 1 letter 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 $qu=new mysqli_swd();$sql="SELECT loginid,username,password FROM loginInfo";$qu->dbsql($sql); $ciphering = "AES-128-CTR";$iv_length = openssl_cipher_iv_length($ciphering);$options = 0;$encryption_iv = '1234567891011121'; $encryption_key = SWD_KEY; if(SWD_KEY!="JesusIsLord"){ECHO "SHIT";EXIT;} for($i=1;$i<=$qu->num;$i++){ $row=$qu->dbRow($qu->data); $username=addslashes(openssl_encrypt($row[1], $ciphering,$encryption_key, $options, $encryption_iv)); $password= addslashes(openssl_encrypt($row[2], $ciphering,$encryption_key, $options, $encryption_iv)); $sql="UPDATE loginInfo SET username='$username',password='$password' WHERE loginid=".$row[0];$r->dbsql($sql); } exit; Php 3 02/22/2024 Php Function SESSION VARIABLES NOT WORKING DEBUG $_SESSION HEMPDBASE " size="20" maxlength="50" required> Php 0 03/02/2024 Php Function Create Lionks Backup links $PDS_ Developer function CreateLinks($inx,$num,$range){ global $ALPHA; global $VIEW;global $txWhere;global $PDS_; $SubCat="&PDS_=";if($PDS_>0)$SubCat="&PDS_=".$PDS_; echo "ododo=".$PDS_; $ratio=(int)($num/$range);$start=1;$maxlinks=30; if($ratio<$num/$range)$ratio+=1; $end=$ratio; if($ratio>$maxlinks){ $start=$inx/$range-$maxlinks/2; if($start<1)$start=1; $end=$start+$maxlinks; if($end>$ratio){ $end=$ratio;$start=$end-$maxlinks; } } for($i=$start;$i<=$end;$i++){ switch($VIEW){ case 2: $submenu.="$i|"; break; default: $submenu.="$i|"; } } $dis1.=$submenu; return $dis1; } Php 0 08/21/2024 Php Function Deletefile.php delete exist file Backup File Info "; switch($AC){ case 1: if(file_exists($upfile))unlink($upfile); $upfile=str_replace("/thm/","/",$upfile); if(file_exists($upfile))unlink($upfile); echo "File is Deleted. Please close this window"; break; default: if(file_exists($upfile)){ if(file_exists($upfile)){ if(mime_content_type($upfile)=="image/jpeg"){ $dimen=sizepicture($upfile,300,400); echo " "; }else{ echo $upfile.""; } echo "If not, just close this window"; } }else echo "This file does not exist. Close this window."; break; } ?> 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 pow(5, 3) (float)$val (int)$val 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 $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>'; echo strip_tags($text); echo "n"; // Allow <p> and <a> echo strip_tags($text, '<p><a>'); // as of PHP 7.4.0 the line above can be written as: // echo strip_tags($text, ['p', 'a']); ?> Php 2 09/09/2023 Php Language PHP Language random Generate randoms "); echo(rand() . ""); echo(rand(10,100)); ?> Definition and Usage The rand() function generates a random integer. Example tip: If you want a random integer between 10 and 100 (inclusive), use rand (10,100). Tip: As of PHP 7.1, the rand() function has been an alias of the mt_rand() function. =====random strings =========== function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[random_int(0, $charactersLength - 1)]; } return $randomString; } Output the random string with the call below: // Echo the random string. echo generateRandomString(); // Optionally, you can give it a desired string length. echo generateRandomString(64); 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 Set $i = 8, then print $i as long as $i is less than 6: $i = 8; do { echo $i; $i++; } while ($i < 6); The code will be executed once, even if the condition is never true. Print $i as long as $i is less than 6: $i = 1; while ($i < 6) { echo $i; $i++; } Stop the loop when $i is 3: $i = 1; while ($i < 6) { if ($i == 3) break; echo $i; $i++; } Stop, and jump to the next iteration if $i is 3: $i = 0; while ($i < 6) { $i++; if ($i == 3) continue; echo $i; } Count to 100 by tens: $i = 0; while ($i < 100) { $i+=10; echo $i ""; } 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 function sizepicture($picture){ $maxwidth=110; $maxheight=110; list($width, $height, $type, $attr) = getimagesize($picture); $hratio=$height/$maxheight; $wratio=$width/$maxwidth; if ($wratio>$hratio){ $ratio=$width/$height; if($width>$maxwidth){ $height=(int)($maxwidth/$ratio);$width=$maxwidth; } }else{ $ratio=$height/$width; if($height>$maxheight){ $width=(int)($maxheight/$ratio);$height=$maxheight; } } $size[0]=$width;$size[1]=$height; return $size; } <?php $picture="../logo/logo14.jpg"; $maxwidth=300; $maxheight=200; list($width, $height, $type, $attr) = getimagesize($picture); $hratio=$height/$maxheight; $wratio=$width/$maxwidth; if ($wratio>$hratio){ $ratio=$width/$height; if($width>$maxwidth){ $height=(int)($maxwidth/$ratio);$width=$maxwidth; } }else{ $ratio=$height/$width; if($height>$maxheight){ $width=(int)($maxheight/$ratio);$height=$maxheight; } } $dis.="<img src='$picture' width=$width height=$height><BR><img src='$picture'>n"; echo $dis; ?> ......................MAKE THUMBNAILS................................... function make_thumb($file) { $image = "/home/dunning/public_html/images/" . $file; $thumb = "/home/dunning/public_html/images/t_" . $file; //echo "Creating thumbnail..." . $thumb . "<br>"; if(!$max_width) $max_width = 199; if(!$max_height) $max_height = 134; $size = GetImageSize($image); $width = $size[0]; $height = $size[1]; $x_ratio = $max_width / $width; $y_ratio = $max_height / $height; if( ($width <= $max_width) && ($height <= $max_height) ) { $tn_width = $width; $tn_height = $height; } else if(($x_ratio * $height) < $max_height) { $tn_height = ceil($x_ratio * $height); $tn_width = $max_width; } else { $tn_width = ceil($y_ratio * $width); $tn_height = $max_height; } $src = imagecreatefromjpeg($image); $dst = imagecreatetruecolor($tn_width, $tn_height); imagecopyresized($dst, $src, 0, 0, 0, 0, $tn_width, $tn_height, $width, $height); imagejpeg($dst, $thumb, 90); imagedestroy($src);//imagedestroy($src, $dst); } ----------FUNCTION.................................. Part I: The HTML Form <form action="upload.php" method="post" enctype="multipart/form-data > <input type="file" name="uploadfile"/> <input type="submit"/> Part II: Getting at the file, resizing the image, and saving to the server. (upload.php) <?php // This is the temporary file created by PHP $uploadedfile = $_FILES['uploadfile']['tmp_name']; // Create an Image from it so we can do the resize $src = imagecreatefromjpeg($uploadedfile); // Capture the original size of the uploaded image list($width,$height)=getimagesize($uploadedfile); // For our purposes, I have resized the image to be // 600 pixels wide, and maintain the original aspect // ratio. This prevents the image from being "stretched" // or "squashed". If you prefer some max width other than // 600, simply change the $newwidth variable $newwidth=600; $newheight=($height/$width)*600; $tmp=imagecreatetruecolor($newwidth,$newheight); // this line actually does the image resizing, copying from the original // image into the $tmp image imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height); // now write the resized image to disk. I have assumed that you want the // resized, uploaded image file to reside in the ./images subdirectory. $filename = "images/". $_FILES['uploadfile']['name']; imagejpeg($tmp,$filename,100); imagedestroy($src); imagedestroy($tmp); // NOTE: PHP will clean up the temp file it created when the request // has completed. ?> ================ 2nd example ============================================ There are some things you will want to keep in mind when use PHP to resize your images. Resizing images in PHP takes CPU time so it's not something that you want to do frequently. Sometimes people will ask me how to create thumbnail images on-the-fly without having to save them to disk every time. This is a bad idea because you will put unnecessary load on your web server and depending on how many visitors you have, your server could crash. It is better to resize the image to thumbnail size and save the thumbnails for later use even though it might take up a little more disk space on your server. Here is the function that I use to resize jpg images. It uses the GD2 library, and as you'll see, it preserves the colors in true color images. <?php function resampimagejpg( $forcedwidth, $forcedheight, $sourcefile, $destfile ) { $fw = $forcedwidth; $fh = $forcedheight; $is = getimagesize( $sourcefile ); if( $is[0] >= $is[1] ) { $orientation = 0; } else { $orientation = 1; $fw = $forcedheight; $fh = $forcedwidth; } if ( $is[0] > $fw || $is[1] > $fh ) { if( ( $is[0] - $fw ) >= ( $is[1] - $fh ) ) { $iw = $fw; $ih = ( $fw / $is[0] ) * $is[1]; } else { $ih = $fh; $iw = ( $ih / $is[1] ) * $is[0]; } $t = 1; } else { $iw = $is[0]; $ih = $is[1]; $t = 2; } if ( $t == 1 ) { $img_src = imagecreatefromjpeg( $sourcefile ); $img_dst = imagecreatetruecolor( $iw, $ih ); imagecopyresampled( $img_dst, $img_src, 0, 0, 0, 0, $iw, $ih, $is[0], $is[1] ); if( !imagejpeg( $img_dst, $destfile, 90 ) ) { exit( ); } } else if ( $t == 2 ) { copy( $sourcefile, $destfile ); } } ?> To use the resize function you must pass in the forced width, forced height, source image, and destination image. The function then uses the GD2 library functions to read the source image's size. It will then calculate the new image's size based off of the forced width and height. This function will maintain the original image's aspect ratio so your image won't look distorted. It won't change the source image at all but when the function is done running you will end up with the destination image which is resized to the dimensions you passed into the function. As far as I know, this function requires the GD2 library although you might be able to get it to work with the GD1 library. The GD library extension must be enabled in PHP before you can use GD2 functions so keep that in mind as well. You can use the PHP function phpinfo() to see if GD2 is enabled or to see what version of the GD library your server is using. Update - March 22nd, 2007 When I originally wrote this article there were not many digital cameras or other devices capable or creating images larger than about 6 megapixels. Now that 7,8, and 10 megapixel cameras are more commonplace, some people who use this resizing function have run into a problem with PHP running out of memory. The problem is that the user's web host has set the PHP memory limit to a low value so that the server's resources can be shared somewhat equally between all the users on the server. Larger files require more memory to resize so when the resizing script hits the memory limit it chokes and gives an internal server error. Possible solutions to the problem: Contact your host and ask them to increase the PHP memory limit so your script can resize the larger files. Use a different program to resize the images such as ImageMagick if your host provides it. If your host does not provide it you may be able to install it yourself if you have shell access available on your hosting account. Don't allow users to upload such large files. It consumes a lot of bandwidth on your server and can be very slow for the user depending on the speed of their internet connection. Have them resize the image before uploading it so that it is under 1MB or so. I hope this PHP function will allow you to resize images easily. It has worked very well for me. ............................ GETIMAGESIZE..................................... Returns an array with 4 elements. Index 0 contains the width of the image in pixels. Index 1 contains the height. Index 2 is a flag indicating the type of the image: 1 = GIF, 2 = JPG, 3 = PNG, 4 = SWF, 5 = PSD, 6 = BMP, 7 = TIFF(intel byte order), 8 = TIFF(motorola byte order), 9 = JPC, 10 = JP2, 11 = JPX, 12 = JB2, 13 = SWC, 14 = IFF. These values correspond to the IMAGETYPE constants that were added in PHP 4.3. Index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag. list($width, $height, $type, $attr) = getimagesize('images/'.$picture); 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 convert a date into a string $dateString = strval($paid_date[$value]); Find postion of something: strpos($string,$character,$offset); Html tags REMOVE: $allowTheseTags="List all tags allowed" echo strip_tags($text, '$allowTheseTags'); Length of: strlen($string) Lower and Upper Case: $stringnew=strtolower($string); $stringnew=strtoupper($string); Replace something with something else: $longadd=str_replace(chr(13),'',$longadd); $string = "The quick brown fox jumps over the lazy dog."; $search = array("","","", "","","{textarea","{/textarea>","{td", "{/td>", "{/tr>","{tr"); // Corresponding replacement substrings $newString = str_replace($search, $replace, $string); echo $newString; // Output: The fast red fox jumps over the sleepy dog. ?> Get section out of something: $newstring=substr($string,int start, int length); [First Caps] $string = strtolower($string); $string = substr_replace($string, strtoupper(substr($string, 0, 1)), 0, 1); [substring] $newstring=substr($string,int start, int length); $url=$row['url']; if($url!=""){ if(substr($url,0,4)=="www.")$url="http://".$url; if(substr($url,0,7)!="http://")$url="http://".$url; } Php 1396 10/21/2025 Php Variables Using Arrays array "35","Ben"=>"37","Joe"=>"43"); arsort($age); ?> Definition and Usage The arsort() function sorts an associative array in descending order, according to the value. Tip: Use the asort() function to sort an associative array in ascending order, according to the value. Tip: Use the krsort() function to sort an associative array in descending order, according to the key. Syntax arsort(array, sorttype) Parameter Values Parameter Description array Required. Specifies the array to sort sorttype Optional. Specifies how to compare the array elements/items. Possible values: 0 = SORT_REGULAR - Default. Compare items normally (don't change types) 1 = SORT_NUMERIC - Compare items numerically 2 = SORT_STRING - Compare items as strings 3 = SORT_LOCALE_STRING - Compare items as strings, based on current locale 4 = SORT_NATURAL - Compare items as strings using natural ordering 5 = SORT_FLAG_CASE - ?> 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 Function EmailCriteria() Dim MV(200, 2) As String, L As Integer Try Dim sqL As String = "SELECT [move_to],[subject_filter],[archive] FROM [move_email] WHERE [archive]>0 ORDER BY [move_to],[subject_filter]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception LAerrorMessage.Text = "error BTbulkMove DB:" & ex.Message End Try Do While dr.Read MV(L, 0) = dr(0) : MV(L, 1) = dr(1) : MV(L, 2) = dr(2) L = L + 1 Loop Return MV End Function Private Sub BTmoveEmail_Click(sender As Object, e As EventArgs) Handles BTmoveEmail.Click BypassDialog = True BTMoveAll_Click(sender, e) BTtest_Click(sender, e) Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email Moving And Deleting completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) BypassDialog = False End Sub Private Sub BTMoveAll_Click(sender As Object, e As EventArgs) Handles BTMoveAll.Click Dim outlookApp As New Outlook.Application() Dim lastFolder As String = "", currentFolder As String = "", currentSubject As String = "", currentType As String = "", currentEmail As String = "" Dim emailsMoved As Int16 = 100, MV(200, 2) As String, L As Integer = 0 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") ' Specify the path to the Outlook Data File (PST) Dim pstFilePath As String = GetIni("OutlookDataFile", My.Computer.Name, INI), TMP As String = "" Dim pstDisplayName As String = "receipts" ' Loop through all accounts in Outlook For Each account As Outlook.Account In namespaceMAPI.Accounts 'LOOP THROUGH ACCOUNTS LAcaption.Text = "Moving in account: " & account.DisplayName : Application.DoEvents() emailsMoved = 100 ' Access the Inbox folder of the account Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTMoveAll:" & ex.Message End Try 'start loop here 'Do While emailsMoved > 0 'LOOP THROUGH FOR MISSED EMAIL emailsMoved = 0 MV = EmailCriteria() For i As Integer = inbox.Items.Count To 1 Step -1 'LOOP THROUGH INBOX backwards LEVEL 2 Try Dim email As Outlook.MailItem = TryCast(inbox.Items(i), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If For L = 0 To MV.GetUpperBound(0) 'MsgBox(fruit) currentFolder = MV(L, 0) : currentSubject = MV(L, 1) : currentType = MV(L, 2) add these lines back If lastFolder <> currentFolder Then lastFolder = currentFolder Try targetFolder = namespaceMAPI.Folders("Outlook Data File").Folders(currentFolder) Catch ex As Exception 'M("Error Outlook Data File: " & ex.Message) 'Continue Do End Try End If Select Case currentType Case "1" 'email If email.SenderEmailAddress.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 Exit For End If Case "2" If email.Subject.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 Exit For End If End Select Next 'NEXT L Catch ex As Exception MsgBox("Error moving: " + currentEmail & ex.Message) End Try Next 'LOOP THROUGH INBOX backwards LEVEL 2 END 'end primary loop 'Loop 'LOOP THROUGH FOR DR 'Loop 'LOOP THROUGH FOR MISSED EMAIL END Next 'LOOP THROUGH ACCOUNTS END If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email moving process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) End Sub Private Sub BTtest_Click(sender As Object, e As EventArgs) Handles BTtest.Click Dim outlookApp As New Outlook.Application() Dim currentEmail As String = "" Dim emailsDeleted As Int16 = 100 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") 'Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim J As Int16, K As Int16, I As Integer = 0, Subject As String = "", FILTER1(200) As String, emailCount As Integer = 0, sql As String = "", Found As Boolean = False 'Readfilter data from mdb Try sql = "SELECT [email] FROM [filtered_email] WHERE [importance]>0 ORDER BY [importance] DESC,[email]" ConnDB() cmd = New OleDbCommand(sql, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) J = 0 Do While dr.Read FILTER1(J) = dr(0) J += 1 Loop emailCount = J - 1 Catch ex As Exception LAerrorMessage.Text = "error BTtestDB:" & ex.Message End Try ' Loop through all accounts in Outlook For Each account As Outlook.Account In namespaceMAPI.Accounts LAcaption.Text = "Deleting In account: " & account.DisplayName : Application.DoEvents() emailsDeleted = 100 ' Access the Inbox folder of the account 'Dim pstRootFolder As Outlook.MAPIFolder = namespaceMAPI.Folders(pstDisplayName) Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTtest account:" & ex.Message End Try 'start loop here Do While emailsDeleted > 0 emailsDeleted = 0 For I = inbox.Items.Count To 1 Step -1 'swd count backwards Try Dim email As Outlook.MailItem = TryCast(inbox.Items(I), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If For K = 0 To emailCount - 1 If email.SenderEmailAddress.Contains(FILTER1(K)) Then Found = True : Exit For Next If Found = False Then email.Delete() emailsDeleted = emailsDeleted + 1 End If Found = False Catch ex As Exception MsgBox(currentEmail & ex.Message) emailsDeleted = emailsDeleted - 1 End Try Next 'end cut A Loop Next If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email Deleting process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) End If End Sub ========================== Outdated ================================ Private Sub BTbulkMove_Click(sender As Object, e As EventArgs) Handles BTbulkMove.Click Dim outlookApp As New Outlook.Application() Dim lastFolder As String = "", currentFolder As String = "", currentSubject As String = "", currentType As Byte = 0, currentEmail As String = "" Dim emailsMoved As Int16 = 100 Dim namespaceMAPI As Outlook.NameSpace = outlookApp.GetNamespace("MAPI") Dim targetFolder As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") Dim inbox As Outlook.MAPIFolder = namespaceMAPI.Folders("Outlook Data File").Folders("receipts") ' Specify the path to the Outlook Data File (PST) Dim pstFilePath As String = GetIni("OutlookDataFile", My.Computer.Name, INI) Dim pstDisplayName As String = "receipts" ' Loop through all accounts in Outlook Try sqL = "SELECT [move_to],[subject_filter],[archive] FROM [move_email] WHERE [archive]>0 ORDER BY [move_to],[subject_filter]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception LAerrorMessage.Text = "error BTbulkMove DB:" & ex.Message End Try For Each account As Outlook.Account In namespaceMAPI.Accounts LAcaption.Text = "Moving in account: " & account.DisplayName : Application.DoEvents() emailsMoved = 100 ' Access the Inbox folder of the account Try inbox = namespaceMAPI.Folders(account.DisplayName).Folders("Inbox") Catch ex As Exception LAerrorMessage.Text = "error BTbulkMoveA:" & ex.Message End Try 'start loop here Do While emailsMoved > 0 emailsMoved = 0 Try sqL = "SELECT [move_to],[subject_filter],[archive] FROM [move_email] WHERE [archive]>0 ORDER BY [move_to],[subject_filter]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception LAerrorMessage.Text = "error BTbulkMove DB:" & ex.Message End Try Do While dr.Read currentFolder = dr(0) : currentSubject = dr(1) : currentType = dr(2) If lastFolder <> currentFolder Then lastFolder = currentFolder Try targetFolder = namespaceMAPI.Folders("Outlook Data File").Folders(currentFolder) Catch ex As Exception 'M("Error Outlook Data File: " & ex.Message) Continue Do End Try End If For i As Integer = inbox.Items.Count To 1 Step -1 'swd count backwards Try Dim email As Outlook.MailItem = TryCast(inbox.Items(i), Outlook.MailItem) currentEmail = email.SenderName + "--" + email.SenderEmailAddress If email.FlagStatus = Outlook.OlFlagStatus.olFlagMarked Then Continue For End If Select Case currentType Case 1 'email If email.SenderEmailAddress.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 End If Case 2 If email.Subject.Contains(currentSubject) Then email.Move(targetFolder) : emailsMoved = emailsMoved + 1 End If End Select Catch ex As Exception MsgBox("Error moving: " + currentEmail & ex.Message) End Try Next Loop Loop Next If BypassDialog = False Then Me.WindowState = FormWindowState.Minimized 'MessageBox.Show("Email moving process completed.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information) Vb.net 7 02/26/2026 Vb.net Controls Combo Box Control combo value archive example txMultiAction.Items.Clear() txMultiAction.ValueMember = "replaceid" txMultiAction.DisplayMember = "title" txMultiAction.DataSource = ds.Tables(Table_) 'created from query. See create recordset txMultiAction.SelectedValue 'read database value ================================================== Private Sub txMultiAction_SelectedIndexChanged(sender As Object, e As EventArgs) Handles txMultiAction.SelectedIndexChanged Dim B1 As String = GetIni("Setup", "cloud", Path.TREE + "MenuJS.ini") If B1 = "" Then B1 = Path.TREE Dim Table_ As String = "mulitreplace WHERE replaceid=" + Str(txMultiAction.SelectedValue) Dim query As String = "SELECT * FROM " & Table_ Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=webtools1.mdb;" Dim ds As New DataSet Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_) cnn.Open() Dim cmd As New OleDbCommand(query, cnn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) cnn.Close() Dim t1 As DataTable = ds.Tables(Table_) 'txMultiAction.Items.Clear() 'txMultiAction.ValueMember = "replaceid" 'txMultiAction.DisplayMember = "title" 'txMultiAction.DataSource = ds.Tables(Table_) Dim row As DataRow Dim Item(2) As String For Each row In t1.Rows Item(0) = row(0) Item(1) = row(1) Item(2) = row(2) MsgBox(Item(2)) 'Dim NextListItem As New ListViewItem(Item) 'ListView1.Items.Add(NextListItem) Next End Sub +++++++++++++++++++++++++++++++++++++++++++++++++ Private Sub btMultiAction_Click(sender As Object, e As EventArgs) Handles btMultiAction.Click Dim fileReader As System.IO.StreamReader, B As String = txText.Text, Action1 As Boolean = False, B1 As String = "" Dim P$(3), POS%(5) Dim A As String = "", A2 As String = "", Action0(-1) As String Dim L10 As Integer = 10, L13 As Integer = 13, Index As Integer = coReplace.SelectedIndex, C1Length As Integer = 0, LOOPOFF As Boolean = False Dim TMPstart As String = "", TMPend As String = "", J As Integer = 0 B1 = GetIni("Setup", "cloud", Path.TREE + "MenuJS.ini") If B1 = "" Then B1 = Path.TREE fileReader = My.Computer.FileSystem.OpenTextFileReader(B1 + "multiaction.txt") Dim stringReader As String ' MsgBox("The first line of the file is " & stringReader) Do Until fileReader.EndOfStream stringReader = fileReader.ReadLine() If stringReader <> "" Then If stringReader.Substring(0, 2) = "[{" Then Action1 = False 'FOUND THE NEXT SECTION. TIME TO STOP READING ON If stringReader = "[{" + txMultiAction.Text + "}]" Then Action1 = True : Continue Do If Action1 = True Then If InStr(stringReader, "?") = 0 Then MsgBox("Invalid Format. A ? needs to be between the search for and replace term", MsgBoxStyle.AbortRetryIgnore) : fileReader.Close() : Exit Sub Action0 = Split(stringReader, "?") : A = Action0(0) : A2 = Action0(1) : If A2 = "NULL" Then A2 = "" 'CREATE LOOKUP STRING AND IDENTIFY REPLACEMENT STRIN Select Case A Case "bof" 'BEGIN OF FILE B = A2 + B Case "eof" 'END OF FILE B = B + A2 Case Is = "lf" 'remove double CrLf B = Replace(B, Chr(10) + Chr(32), Chr(10)) 'remove spaces after feeds 'If InStr(B, Chr(13) + Chr(10)) > InStr(B, Chr(10) + Chr(13)) Then L10 = 13 : L13 = 10:B = Replace(B, Chr(L13) + Chr(L10) + Chr(L13) + Chr(L10), Chr(13) + Chr(10)):B = Replace(B, Chr(13) + Chr(13), Chr(13)) B = Replace(B, Chr(10) + Chr(10), Chr(10)) 'Double feeds to single Case Is = "td" 'Replace tabs with dash B = Replace(B, Chr(9), " - ") Case Is = "ts" 'tab to spaces B = Replace(B, Chr(9), Chr(32)) : B = Replace(B, Chr(32) + Chr(32), Chr(32)) Case Is = "tc" 'tab to comma B = Replace(B, Chr(9), ", ") : B = Replace(B, Chr(32) + ",", ",") Case Is = "lfc" 'replace line feeds with commas B = Replace(B, Chr(10), ", ") B = Replace(B, Chr(10), ", ") : B = Replace(B, ",,", ",") : B = Replace(B, Chr(9), Chr(32)) Case Is = "lb-" 'Replace line breaks with - B = Replace(B, Chr(10), " - ") : B = Replace(B, Chr(9), Chr(32)) : B = Replace(B, Chr(32) + Chr(32), Chr(32)) Case Is = "{GET}" 'EXTRACT BETWEEN { } Dim POS1(3) As Integer POS1(3) = 1 : A2 = "" Do POS1(0) = InStr(POS1(3), B, "{") : POS1(3) = POS1(0) + 1 : POS1(1) = InStr(POS1(3), B, "}") If POS1(0) = 0 Or POS1(1) = 0 Then Exit Do A2 = A2 + B.Substring(POS1(0), POS1(1) - POS1(0) - 1) + vbCrLf Loop If A2 <> "" Then B = A2 Case Is = "{DEL}" 'Delete BETWEEN { } Dim POS1(3) As Integer POS1(3) = 1 Do POS1(0) = InStr(POS1(3), B, "{") If POS1(0) = 0 Then Exit Do POS1(3) = POS1(0) : POS1(1) = InStr(POS1(3), B, "}") : A2 = "" If POS1(0) > 1 Then A2 = B.Substring(0, POS1(0) - 1) B = A2 + B.Substring(POS1(1), B.Length - POS1(1)) 'Build string without first {} Loop Case Else If chAppendCRLF.Checked = True Then A = Replace(A, "|", Chr(10)) : A2 = Replace(A2, "|", Chr(10)) 'REPLACE LINE BREAKS IF IDENTIFIED End If If chAciiConversion.Checked = True Then 'THIS DOES ASCII SOMETHING L10 = InStr(A, "~") If L10 > 0 Then L13 = InStr(L10 + 1, A, "~") End If If L10 > 0 And L13 > 0 Then If L10 > 1 Then TMPstart = A.Substring(0, L10 - 1) If L13 < A.Length Then TMPend = A.Substring(L13, A.Length - L13) A = Chr(Val(A.Substring(L10, L13 - L10 - 1))) End If A = TMPstart + A + TMPend : TMPstart = "" : TMPend = "" 'MsgBox(A) L10 = 0 : L13 = 0 : L10 = InStr(A2, "~") If L10 > 0 Then L13 = InStr(L10 + 1, A2, "~") End If If L10 > 0 And L13 > 0 Then If L10 > 0 And L13 > 0 Then If L10 > 1 Then TMPstart = A2.Substring(0, L10 - 1) If L13 < A2.Length Then TMPend = A2.Substring(L13, A2.Length - L13) A2 = Chr(Val(A2.Substring(L10, L13 - L10 - 1))) End If A2 = TMPstart + A2 + TMPend : TMPstart = "" : TMPend = "" End If End If B = Replace(B, A, A2) End Select End If Loop fileReader.Close() : txText.Text = B End Sub 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 Imports System.Data.Oledb Solution Beta1 'Grabs data from a table and posts it into a ListView Dim Table_ As String = "mulitreplace ORDER BY title" Dim query As String = "SELECT * FROM " & Table_ Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=webtools1.mdb;" Dim ds As New DataSet Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_) cnn.Open() Dim cmd As New OleDbCommand(query, cnn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) cnn.Close() Dim t1 As DataTable = ds.Tables(Table_) txMultiAction.Items.Clear() txMultiAction.ValueMember = "replaceid" txMultiAction.DisplayMember = "title" txMultiAction.DataSource = ds.Tables(Table_) Dim row As DataRow Dim Item(2) As String For Each row In t1.Rows Item(0) = row(0) Item(1) = row(1) Item(2) = row(2) 'MsgBox(Item(1)) 'Dim NextListItem As New ListViewItem(Item) 'ListView1.Items.Add(NextListItem) Next 'end Beta Dim con As New OledbConnection("Provider=microsoft.Jet.oledb.4.0DataSource=D:mydata.mdb;") Dim cmd As New OledbCommand Public var1 As String Public Sub New() con.Open() cmd.Connection = con cmd.CommandText = "SELECT * FROM table1" End Sub Public Sub creates() cmd.CommandText = "INSERT INTO table1(Neyms) VALUES('" + var1 + "')" cmd.ExecuteNonQuery() End Sub Permalink Posted 16-Jan-13 22:39pm vinodkumarnie Solution 2 Grabs data from a table and posts it into a ListView Dim Table_ As String = "Table1" Dim query As String = "SELECT * FROM " & Table_ Dim MDBConnString_ As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=TestDatabase.mdb;" Dim ds As New DataSet Dim cnn As OleDbConnection = New OleDbConnection(MDBConnString_) cnn.Open() Dim cmd As New OleDbCommand(query, cnn) Dim da As New OleDbDataAdapter(cmd) da.Fill(ds, Table_) cnn.Close() Dim t1 As DataTable = ds.Tables(Table_) Dim row As DataRow Dim Item(2) As String For Each row In t1.Rows Item(0) = row(0) Item(1) = row(1) Dim NextListItem As New ListViewItem(Item) ListView1.Items.Add(NextListItem) Next Vb.net 2 09/09/2023 Vb.net Database Delete A Record From A DAO Recordset delete recordset Sub DeleteDuplicateShippers() Dim dbsNorthwind As DAO.Database Dim rstShippers As DAO.Recordset Dim strSQL As String Dim strName As String On Error GoTo ErrorHandler Set dbsNorthwind = CurrentDb strSQL = "SELECT * FROM Shippers ORDER BY CompanyName, ShipperID" Set rstShippers = dbsNorthwind.OpenRecordset(strSQL, dbOpenDynaset) ' If no records in Shippers table, exit. If rstShippers.EOF Then Exit Sub strName = rstShippers![CompanyName] rstShippers.MoveNext Do Until rstShippers.EOF If rstShippers![CompanyName] = strName Then rstShippers.Delete Else strName = rstShippers![CompanyName] End If rstShippers.MoveNext Loop Exit Sub ErrorHandler: MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description End Function Vb.net 0 10/09/2022 Vb.net Database Extract Data From A Record In A DAO Recordset extreact recordset After you have located a particular record or records, you may want to extract data to use in your application instead of modifying the underlying source table. Copy a single field You can copy a single field of a record to a variable of the appropriate data type. The following example extracts three fields from the first record in a Recordset object. VB Copy Dim dbsNorthwind As DAO.Database Dim rstEmployees As DAO.Recordset Dim strFirstName As String Dim strLastName As String Dim strTitle As String Set dbsNorthwind = CurrentDb Set rstEmployees = dbsNorthwind.OpenRecordset("Employees") rstEmployees.MoveFirst strFirstName = rstEmployees!FirstName strLastName = rstEmployees!LastName strTitle = rstEmployees!Title Copy entire records to an array To copy one or more records, you can create a two-dimensional array and copy records one at a time. You increment the first subscript for each field and the second subscript for each record. A fast way to do this is to use the GetRows method, which returns a two-dimensional array. The first subscript identifies the field and the second identifies the row number, as follows. VB Copy varRecords(intField, intRecord) The following code example uses an SQL statement to retrieve three fields from a table called Employees into a Recordset object. It then uses the GetRows method to retrieve the first three records of the Recordset, and it stores the selected records in a two-dimensional array. It then prints each record, one field at a time, by using the two array indexes to select specific fields and records. To show how the array indexes are used, the following example uses a separate statement to identify and print each field of each record. In practice, it would be more reliable to use two loops, one nested in the other, and to provide integer variables for the indexes that step through both dimensions of the array. VB Copy Sub GetRowsTest() Dim dbsNorthwind As DAO.Database Dim rstEmployees As DAO.Recordset Dim varRecords As Variant Dim intNumReturned As Integer Dim intNumColumns As Integer Dim intColumn As Integer Dim intRow As Integer Dim strSQL As String On Error GoTo ErrorHandler Set dbsNorthwind = CurrentDb strSQL = "SELECT FirstName, LastName, Title FROM Employees" Set rstEmployees = dbsNorthwind.OpenRecordset(strSQL, dbOpenSnapshot) varRecords = rstEmployees.GetRows(3) intNumReturned = UBound(varRecords, 2) + 1 intNumColumns = UBound(varRecords, 1) + 1 For intRow = 0 To intNumReturned - 1 For intColumn = 0 To intNumColumns - 1 Debug.Print varRecords(intColumn, intRow) Next intColumn Next intRow rstEmployees.Close dbsNorthwind.Close Set rstEmployees = Nothing Set dbsNorthwind = Nothing Exit Sub ErrorHandler: MsgBox "Error #: " & Err.Number & vbCrLf & vbCrLf & Err.Description End Sub Use subsequent calls to the GetRows method if more records are available. Because the array is filled as soon as you call the GetRows method, you can see why this approach is much faster than copying one field at a time. Notice also that you don't have to declare the Variant as an array, because this is done automatically when the GetRows method returns records. This enables you to use fixed-length array dimensions without knowing how many records or fields will be returned, instead of using variable-length dimensions that take up more memory. If you are trying to retrieve all the rows by using multiple GetRows calls, use the EOF property to be sure that you are at the end of the Recordset. The GetRows method may return fewer rows than you request. If you request more than the remaining number of rows in a Recordset, for example, the GetRows method returns only the rows that remain. Similarly, if it cannot retrieve a row in the range requested, it does not return that row. For example, if the fifth record cannot be retrieved in a group of 10 records that you are trying to retrieve, the GetRows method returns four records and leaves the current record position on the record that caused a problem, and does not generate a run-time error. This situation may occur if a record in a dynaset was deleted by another user. If it returns fewer records than the number requested and you are not at the end of the file, you need to read each field in the current record to determine what error the GetRows method encountered. Because the GetRows method always returns all the fields in the Recordset object, you may want to create a query that returns just the fields that you need. This is especially important for OLE Object and Memo fields. Vb.net 2 09/09/2023 Vb.net Database Using The Datagridview Control datagrid access mdb view access developer using a tab system Private Sub tab1_Selected(ByVal sender As Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles tab1.Selected If tab1.SelectedTab.Text = "Text Convert" Then If txMultiAction.Items.Count = 0 Then Call LoadMultipleCombo() End If If tab1.SelectedTab.Text = "Database" Then btRefresh_Click(sender, e) End If End Sub ==================== Private Sub btRefresh_Click(sender As Object, e As EventArgs) Handles btRefresh.Click txSectionCode.Height = 400 With DataGridView1 .SelectionMode = DataGridViewSelectionMode.FullRowSelect .Width = 1150 .Columns.Add("switchid", "switchid") : .Columns.Add("position", "Position") : .Columns.Add("code", "code") : .Columns.Add("Description", "Description") .Columns(0).Visible = False .Columns(1).HeaderText = "Title" .Columns(2).HeaderText = "Code" .Columns(1).Width = 300 : .Columns(2).Width = 1200 Try sqL = "SELECT [replaceid],[title],[section_code] FROM [mulitreplace] order by [title]" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) .Rows.Clear() Do While dr.Read .Rows.Add(dr(0), dr(1), dr(2)) Loop Catch ex As Exception MsgBox(ex.Message) End Try End With End Sub ==================== Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click Try sqL = "INSERT INTO [mulitreplace]([title],[section_code]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text) End Sub ------------------------------------------------------- Private Sub btAdd_Click(sender As Object, e As EventArgs) Handles btAdd.Click Try sqL = "INSERT INTO [mulitreplace]([title],[section_code]) VALUES ('" + txTitle.Text + "', '" + txSectionCode.Text + "')" ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try DataGridView1.Rows.Add(0, txTitle.Text, txSectionCode.Text) End Sub -------------------------------------------------- Private Sub DataGridView1_MouseClick(sender As Object, e As MouseEventArgs) Handles DataGridView1.MouseClick Try Dim dr As DataGridViewRow = DataGridView1.SelectedRows(0) txReplaceid.Text = dr.Cells(0).Value.ToString() txTitle.Text = dr.Cells(1).Value.ToString() txSectionCode.Text = dr.Cells(2).Value.ToString() Catch ex As Exception MsgBox(Err.ToString) End Try End Sub ----------------------------------------------- Private Sub btUpdate_Click(sender As Object, e As EventArgs) Handles btUpdate.Click Dim update As DataGridViewRow = DataGridView1.SelectedRows(0) If txReplaceid.Text = "0" Then MsgBox("You cannot edit new records without refresh.") : Exit Sub update.Cells(1).Value = txTitle.Text update.Cells(2).Value = txSectionCode.Text Try sqL = "UPDATE [mulitreplace] SET [title]='" + txTitle.Text + "',[section_code]='" + txSectionCode.Text + "' WHERE [replaceid]=" + txReplaceid.Text ConnDB() cmd = New OleDbCommand(sqL, conn) dr = cmd.ExecuteReader(CommandBehavior.CloseConnection) Catch ex As Exception MsgBox(ex.Message) End Try End Sub ============== MODULE ============== Imports System.Data.OleDb Module ModConnection Public cur As Form Public dt As DataTable Public conn As OleDbConnection Public cmd As OleDbCommand Public dr As OleDbDataReader Public da As OleDbDataAdapter Public ds As DataSet Public sqL As String Public Sub ConnDB() 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 'C:UserssteveDropboxvb10fileExplorerfileExplorerbinReleasePHPCreator.mdb" Try Dim connectionString As String = "Provider=Microsoft.jet.oledb.4.0;Data Source=" + R 'Dim connectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + R conn = New OleDbConnection(connectionString) 'conn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath() & "beer.mdb;") 'conn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:Databasephone.mdb;Jet OLEDB:Database Password = escobar;") conn.Open() Catch ex As Exception MsgBox("Failed in Connecting to database") End Try End Sub Public Function getDataTable(ByVal SQL As String) As DataTable ConnDB() Dim cmd As New OleDbCommand(SQL, conn) Dim dt As New DataTable Dim da As New OleDbDataAdapter(cmd) da.Fill(dt) Return dt End Function End Module Vb.net 4 02/06/2025