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 Files Activate75.php activate security Developer //require_once($_SERVER['DOCUMENT_ROOT']."/activate75.php"); if($bypass!=true){ $appid="636390303046554890"; $user='softwax3_build99';$password='Web2Build.now';$database='softwax3_SoftwareUsers'; $connection = swd_mysql("localhost", $user,$password,$database); //if($appid>"636390303046554897"){$qu=new mysqli_swd();}else{$qu=new dbase();} $qu=new mysqli_swd(); $sql="SELECT lock_device,security_level FROM users WHERE device_name='".$_COOKIE["machine_id"]."'"; $qu->dbsql($sql); if($qu->num==0 || $qu->data1[0]==1) { echo "You are locked out";exit; } $_SESSION['LEVEL']=$qu->data1[1]; $LEVEL=$qu->data1[1]; define('SWD_AUTHENTICATE', true);define('SWD_KEY', 'JesusIsLord'); } if($bypass==true){define('SWD_AUTHENTICATE', true);} ?> Php 0 05/11/2025 Php Date Add Day add day $date = date('m/d/Y',strtotime($date.' + 2 days')); [compare difference] $date = date('Y-m-d',strtotime(date('Y-m-d').' + 10 days')); $priority="";if(strtotime($date)>strtotime($daterequested)) $priority="!"; [Subraction] $date = date('Y-m-d',strtotime(date('Y-m-d'))-(10*24*60*60)); "; echo (31*24); ?> Php 3 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 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 Files Clean Url ? url clean & # if you ever add variables to the url line you need to use this function urldecode for passing gets. $urlpart1=urldecode($urlpart1); $urlpart2=urldecode($urlpart2); $url="http://www.mydomain.com?$urlpart1&$urlpart2; Do not use it on a completed url. It will totally mess everything up. Php 1325 09/09/2023 Php Archive Code Zoom Backup Code zoom format html_entity_decode Codezoom.php <?php //compiled version: 7.2022.912.1815 $REPORT_builder.="<script> function Clipboard(txt) { var copyText = document.getElementById(txt); copyText.select(); copyText.setSelectionRange(0, 99999); navigator.clipboard.writeText(copyText.value); }</script>"; $pageLevel=3; $title="code View"; // `Startup Config` embed point $appid="638069743707776546";$appidLast=""; error_reporting( error_reporting() & ~E_NOTICE ); require_once("mystuff.php"); require_once("functions.php"); $r=new mysqli_swd(); //if(file_exists("header_global.php")) require_once("header_global.php"); //if(file_exists("header.php")){ include("header.php"); }else{ echo $REPORT_builder; } $codeid=$_GET["PID"]; //$codeid = ereg_replace('[^0-9]', '', $codeid); $sql="SELECT code,viewed,viewed_date,show_html FROM code WHERE codeid = '$codeid'"; $r->dbsql($sql); $code=html_entity_decode(stripslashes($r->data1[0])); $sql="UPDATE `code` SET `viewed`='".($r->data1[1]+1)."',`viewed_date`='".date("Y-m-d")."' WHERE codeid = '$codeid'";$r->dbsql($sql); $REPORT_builder.="<div class='div1'><textarea id='code' name='code' style=min-height:500px;width:100%;>$code</textarea></div> <input type='button' name='keywords_clipboard' style='margin-top:25px;' value='Save Code' onclick="Clipboard('code');"> <input type=button onclick="location.href='codeView.php?BACK=1#$codeid';" value='R E T U R N'> </body></html>"; echo $REPORT_builder; ?> Php 0 12/28/2022 Php Archive Color Change Script color convert javascript step Home Page div {float:left;} ---------------- ---------------- -------------------- ---Test---- R: G: B: Try it yourself: R: G: B:Transfer RGB Color Values Color Hex Code Color Hex Code Color Hex Code Alice blue #F0F8FF Antique white #FAEBD7 Aqua #00FFFF Aquamarine #7FFFD4 Azure #F0FFFF Beige #F5F5DC Bisque #FFE4C4 Black #000000 Blanche dalmond #FFEBCD Blue #0000FF Blue violet #8A2BE2 Brown #A52A2A Burlywood #DEB887 Cadet blue #5F9EA0 Chartreuse #7FFF00 Chocolate #D2691E Coral #FF7F50 Cornflower blue #6495ED Cornsilk #FFF8DC Crimson #DC143C Cyan #00FFFF Dark blue #00008B Dark cyan #008B8B Dark goldenrod #B8860B Dark gray #A9A9A9 Dark green #006400 Dark khaki #BDB76B Dark magenta #8B008B Dark olive green #556B2F Dark orange #FF8C00 Dark orchid #9932CC Dark red #8B0000 Dark salmon #E9967A Dark seagreen #8DBC8F Dark slate blue #483D8B Dark slate gray #2F4F4F Dark turquoise #00DED1 Dark violet #9400D3 Deep pink #FF1493 Deep sky blue #00BFFF Dim gray #696969 Dodger blue #1E90FF Firebrick #B22222 Floral white #FFFAF0 Forest green #228B22 Fuchsia #FF00FF Gainsboro #DCDCDC Ghost white #F8F8FF Gold #FFD700 Goldenrod #DAA520 Gray #808080 Green #008000 Green yellow #ADFF2F Honeydew #F0FFF0 Hot pink #FF69B4 Indian red #CD5C5C Indigo #4B0082 Ivory #FFFFF0 Khaki #F0E68C Lavender #E6E6FA Lavender blush #FFF0F5 Lawngreen #7CFC00 Lemon chiffon #FFFACD Light blue #ADD8E6 Light coral #F08080 Light cyan #E0FFFF Light goldenrod yellow #FAFAD2 Light green #90EE90 Light grey #D3D3D3 Light pink #FFB6C1 Light salmon #FFA07A Light seagreen #20B2AA Light sky blue #87CEFA Light slate gray #778899 Light steel blue #B0C4DE Light yellow #FFFFE0 Lime #00FF00 Lime green #32CD32 Linen #FAF0E6 Magenta #FF00FF Maroon #800000 Medium aquamarine #66CDAA Medium blue #0000CD Medium orchid #BA55D3 Medium purple #9370DB Medium sea green #3CB371 Medium slate blue #7B68EE Medium spring green #00FA9A Medium turquoise #48D1CC Medium violet red #C71585 Midnight blue #191970 Mint cream #F5FFFA Misty rose #FFE4E1 Moccasin #FFE4B5 Navajo white #FFDEAD Navy #000080 Old lace #FDF5E6 Olive drab #6B8E23 Orange #FFA500 Orange red #FF4500 Orchid #DA70D6 Pale goldenrod #EEE8AA Pale green #98FB98 Pale turquoise #AFEEEE Pale violet red #DB7093 Papaya whip #FFEFD5 Peach puff #FFDAB9 Peru #CD853F Pink #FFC8CB Plum #DDA0DD Powder blue #B0E0E6 Purple #800080 Red #FF0000 Rosy brown #BC8F8F Royal blue #4169E1 Saddle brown #8B4513 Salmon #FA8072 Sandy brown #F4A460 Sea green #2E8B57 Sea shell #FFF5EE Sienna #A0522D Silver #C0C0C0 Sky blue #87CEEB Slate blue #6A5ACD Snow #FFFAFA Spring green #00FF7F Steelblue #4682B4 Tan #D2B48C Teal #008080 Thistle #D8BFD8 Tomato #FF6347 Turquoise #40E0D0 Violet #EE82EE Wheat #F5DEB3 White #FFFFFF Whitesmoke #F5F5F5 Yellow #FFFF00 Yellow green #9ACD32 "; Php 7 12/28/2022 Php Database Concat - Combine Fields Or Text add join concat APENDING data before and after a field. UPDATE `iwspackage` SET iwspackageimg=CONCAT('package',packageid,'.jpg'); UPDATE ads SET img1=CONCAT(adid,'a.jpg'), img2=CONCAT(adid,'b.jpg') , img3=CONCAT(adid,'c.jpg') , img4=CONCAT(adid,'d.jpg'), pdf=CONCAT(adid,'.pdf') WHERE adid>7; Php 2 09/09/2023 Php Files Config.php config Config.php config.php-> require_once($_SERVER['DOCUMENT_ROOT']."/activate75.php"); if($_SERVER['REMOTE_ADDR']=="127.0.0.1"){ $server='localhost';$user='greatone';$password='gr38t0n3';$database='hairshoppe'; $_SESSION['LEVEL']=10; $_SESSION["EMPLOYEE"]=1;} else{ $server='localhost';$user='softwax3_Steve99';$password='pay99.bill';$database='softwax3_hairShoppe'; }// if($_SESSION['EMPLOYEE']==""){ echo "Login Again";exit; } } $LEVEL=$_SESSION['LEVEL'];$debug=true;$domain="softwarewebdesign.com|127.0.0.1"; $sessionListSave="EMPLOYEE";$lightbox="https://www.softwarewebdesign.com"; define('SWD_KEY', 'KingOfKings'); setcookie("humans_21909", "", time() - 3600, "/"); //define('SWD_AUTHENTICATE', true); // inactivate75.php activate75.php -> if($bypass!=true){ $user='softwax3_build99';$password='Web2Build.now';$database='softwax3_SoftwareUsers'; $connection = swd_mysql("localhost", $user,$password,$database); //if($appid>"636390303046554897"){$qu=new mysqli_swd();}else{$qu=new dbase();} $qu=new mysqli_swd(); $sql="SELECT lock_device FROM users WHERE device_name='".$_COOKIE["machine_id"]."'"; $qu->dbsql($sql); if($qu->num==0 || $qu->data1[0]==1) { echo "You are locked out";exit; } $_SESSION['LEVEL']=10; mysqli_close($connection); define('SWD_AUTHENTICATE', true); }define('SWD_KEY', 'JesusIsLord'); if($bypass==true){define('SWD_AUTHENTICATE', true);} Php 1 05/11/2025 Php Customizing Convert Words Into A Graphic text graphic image convert $im = imagecreate(400, 30); // Create some colors $white = imagecolorallocate($im, 255, 255, 255); $grey = imagecolorallocate($im, 128, 128, 128); $black = imagecolorallocate($im, 0, 0, 0); // The text to draw $text = 'Testing...'; // Replace path by your own font path $font = 'arial.ttf'; // Add some shadow to the text imagettftext($im, 20, 0, 11, 21, $grey, $font, $text); // Add the text imagettftext($im, 20, 0, 10, 20, $black, $font, $text); // Using imagepng() results in clearer text compared with imagejpeg() imagepng($im); imagedestroy($im); ************************************* The below script would be called with a tag like this from a page: Header("Content-type: image/gif"); if(!isset($s)) $s=11; $size = imagettfbbox($s,0,"/fonts/TIMES.TTF",$text); $dx = abs($size[2]-$size[0]); $dy = abs($size[5]-$size[3]); $xpad=9; $ypad=9; $im = imagecreate($dx+$xpad,$dy+$ypad); $blue = ImageColorAllocate($im, 0x2c,0x6D,0xAF); $black = ImageColorAllocate($im, 0,0,0); $white = ImageColorAllocate($im, 255,255,255); ImageRectangle($im,0,0,$dx+$xpad-1,$dy+$ypad-1,$black); ImageRectangle($im,0,0,$dx+$xpad,$dy+$ypad,$white); ImageTTFText($im, $s, 0, (int)($xpad/2)+1, $dy+(int)($ypad/2), $black, "/fonts/TIMES.TTF", $text); ImageTTFText($im, $s, 0, (int)($xpad/2), $dy+(int)($ypad/2)-1, $white, "/fonts/TIMES.TTF", $text); ImageGif($im); ImageDestroy($im); ?> It is very important to realize that you cannot put any HTML tags in this file. There should also not be any spaces or blank lines before or after the and ?> tags. If you are getting a broken image using this script, chances are you have a stray carriage return somewhere outside the PHP tags Php 1860 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 Php Files Copy A File In PHP file copy Copying Files To copy a file in PHP, you use the built-in copy() function. This function takes the source file path and the destination path as arguments and returns true on success or false on failure. Syntax php bool copy(string $source, string $destination, resource $context = null): bool $source (Required): The path to the original file you want to copy. $destination (Required): The path, including the new filename, where the file will be copied. If the destination file already exists, it will be overwritten. $context (Optional): A context resource created with stream_context_create(). Example Here is a basic example of how to copy a file and check the result: =?php // Specify the source file path $source_file = 'path/to/original_file.txt'; // Specify the destination path, including the new filename $destination_file = 'path/to/new_directory/copied_file.txt'; // Use the copy() function if (copy($source_file, $destination_file)) { echo "File copied successfully!"; } else { echo "Something went wrong while copying the file. Check permissions."; } ?= Important Considerations File Permissions: The PHP script must have permission to read the source file and write to the destination directory. Permission errors are a common reason for failure. Destination Path: The destination must include the new filename, not just the directory name. For example, you need .../new_dir/copied.txt, not just .../new_dir/. Error Handling: The copy() function returns a boolean, so it is important to use an if statement to handle potential errors gracefully. Moving vs. Copying: If you want to move a file (delete the original after copying), use the rename() function instead. Uploaded Files: For handling files uploaded via an HTML form (HTTP POST method), you must use the specialized move_uploaded_file() function, not copy(). Php 0 12/20/2025 Php Database Count count query count records that link to same file $sql="SELECT * FROM eqMaintenance WHERE maintenanceid = $value_"; $r->dbsql($sql);$row=$r->data1; $upfile="../maintenance/".$row['img']; Start count query $sql="SELECT count(img) as dog FROM eqMaintenance WHERE img='".$row['img']."' GROUP BY img"; $r->dbsql($sql);$dog=$r->data1[0]; if(file_exists($upfile) && $dog<2)unlink($upfile); //example from php file creator SELECT hide,count(hide) as dog FROM `invoice` GROUP BY hide LIMIT 0, 30 SELECT invoices.customerid, `last_name` , `first_name`, COUNT(`last_name`) AS dog, count(if(`date`< ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year1, count(if(`date`>= ADDDATE(NOW(), INTERVAL -365 DAY), 1, null)) AS year0, count(if(`date`< ADDDATE(NOW(), INTERVAL -730 DAY), 1, null)) AS year2 FROM `invoices` INNER JOIN `customer` ON customer.customerid = invoices.customerid GROUP BY invoices.customerid, `last_name` , `first_name` ORDER BY year0,year1 Php 3 12/28/2023 Php Files Create Directory File List After Database Backup file list database backup example Backup Sites %s', escapeshellarg($host), escapeshellarg($user), escapeshellarg($pass), escapeshellarg($dbname), escapeshellarg($filename) ); $output = []; $result_code = 0; // Execute the command exec($command, $output, $result_code); if ($result_code === 0) { return "Database dump successful."; } else { return "Error creating database dump. Command output: " . implode("n", $output); } } // Configuration variables //$server='localhost';$user='softwax3_Steve99';$password='pay99.bill';$database='softwax3_accounting'; $DBHOST = $server; $DBUSER = $user; $DBPASS = $password; $DBNAME = $database; $BACKUP_FILE = 'backup_'.$database. date('Y-m-d_H-i-s') . '.sql'; // Run the backup function $message = backup_mysql_database($DBHOST, $DBUSER, $DBPASS, $DBNAME, $BACKUP_FILE); echo $message; $newname=str_replace(".sql",".txt",$BACKUP_FILE); rename($BACKUP_FILE, $newname); $current_dir="./"; $dir = opendir($current_dir); echo "directory=".$current_dir; while ($file = readdir($dir)){ $fullpath=$current_dir.$file; $filedate=date('Y-m-j', filemtime($fullpath)); $fsize=filesize($fullpath)/1000; $fsize=(int)$fsize;$fsize=$fsize/1000; $bulletin[]=$file."@".$fsize."@".$filedate; } closedir($dir); $count1=count($bulletin); sort($bulletin); reset($bulletin); //if($DI=='')ECHO "?DI="; $dis.="Files(by Name)"; //while (list ($key, $val) = each ($bulletin)){ foreach($bulletin as $key=>$val) { //} while (list ($key, $val) = each ($bulletin)){ $mark=explode('@',$val); $count+=1; if($mark[0]=="index.php")continue; if(strpos($mark[0],".")==0) $dis.="".$mark[0]."Directory"; else $dis.="".$mark[0]."(".$mark[1].") MB ".$mark[2].""; //if($count==(int)($count1/2)) echo " "; } $dis.=""; echo $dis; ?> Php 0 12/19/2025 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 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 Date Current Date today $now=date('Y-m-j'); echo date("Y-m-d h:i:sa"); mysql MySQL FORMAT (yyyy-mm-dd) Php 2 09/09/2023 Php Date Date Functions time date $sessionid=strtotime(date("Y-m-d H:i:s")); format character Description Example returned values a Lowercase Ante meridiem and Post meridiem am or pm A Uppercase Ante meridiem and Post meridiem AM or PM B Swatch Internet time 000 through 999 c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00 d Day of the month, 2 digits with leading zeros 01 to 31 D A textual representation of a day, three letters Mon through Sun F A full textual representation of a month, such as January or March January through December g 12-hour format of an hour without leading zeros 1 through 12 G 24-hour format of an hour without leading zeros 0 through 23 h 12-hour format of an hour with leading zeros 01 through 12 H 24-hour format of an hour with leading zeros 00 through 23 i Minutes with leading zeros 00 to 59 I (capital i) Whether or not the date is in daylights savings time 1 if Daylight Savings Time, 0 otherwise. j Day of the month without leading zeros 1 to 31 l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday L Whether it's a leap year 1 if it is a leap year, 0 otherwise. m Numeric representation of a month, with leading zeros 01 through 12 M A short textual representation of a month, three letters Jan through Dec n Numeric representation of a month, without leading zeros 1 through 12 O Difference to Greenwich time (GMT) in hours Example: +0200 r RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200 s Seconds, with leading zeros 00 through 59 S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j t Number of days in the given month 28 through 31 T Timezone setting of this machine Examples: EST, MDT ... U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time() w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday) W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year) Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003 y A two digit representation of a year Examples: 99 or 03 z The day of the year (starting from 0) 0 through 365 Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 43200 Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate(). Example 1. date() examples **************************************** a "am" or "pm" A "AM" or "PM" B Swatch Internet time d day of the month, 2 digits with leading zeros; i.e. "01" to "31" D day of the week, textual, 3 letters; i.e. "Fri" F month, textual, long; i.e. "January" g hour, 12-hour format without leading zeros; i.e. "1" to "12" G hour, 24-hour format without leading zeros; i.e. "0" to "23" h hour, 12-hour format; i.e. "01" to "12" H hour, 24-hour format; i.e. "00" to "23" i minutes; i.e. "00" to "59" I (capital i) "1" if Daylight Savings Time, "0" otherwise. j day of the month without leading zeros; i.e. "1" to "31" l (lowercase 'L') day of the week, textual, long; i.e. "Friday" L boolean for whether it is a leap year; i.e. "0" or "1" m month; i.e. "01" to "12" M month, textual, 3 letters; i.e. "Jan" n month without leading zeros; i.e. "1" to "12" r RFC 822 formatted date; i.e. "Thu, 21 Dec 2000 16:01:07 +0200" (added in PHP 4.0.4) s seconds; i.e. "00" to "59" S English ordinal suffix, textual, 2 characters; i.e. "th", "nd" t number of days in the given month; i.e. "28" to "31" T Timezone setting of this machine; i.e. "MDT" U seconds since the epoch w day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) Y year, 4 digits; i.e. "1999" y year, 2 digits; i.e. "99" z day of the year; i.e. "0" to "365" Z timezone offset in seconds (i.e. "-43200" to "43200"). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive Php 2090 09/09/2023 Php Database Delete left join delete orphans // using Left Join to kill orphans DELETE FROM `cart` USING `cart` LEFT JOIN orders ON cart.sessionid=orders.sessionid WHERE orderid IS NULL AND updated<'2006-01-01' Php 2 09/09/2023 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 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 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 Files Download Files While Changing Name download header $filename = "theDownloadedFileIsCalledThis.mp3"; $myFile = "/absolute/path/to/my/file.mp3"; $mm_type="application/octet-stream"; header("Cache-Control: public, must-revalidate"); header("Pragma: hack"); // WTF? oh well, it works... header("Content-Type: " . $mm_type); header("Content-Length: " .(string)(filesize($myFile)) ); header('Content-Disposition: attachment; filename="'.$filename.'"'); header("Content-Transfer-Encoding: binaryn"); readfile($myFile); Php 1402 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 Database Find Orphans left join orphan delete // Child to parent using left join to find orphans Select * from table1groups left join table1 on table1groups.musgraveid=table1.musgraveid LIMIT 0, 30 Select * from table1groups left join table1 on table1groups.musgraveid=table1.musgraveid Where table1.musgraveid IS NULL LIMIT 0, 30 Select * from `customer` left join invoices on `customer.customerid`=invoices.customerid Where invoices.customerid IS NULL LIMIT 0, 300 Php 2 09/09/2023 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 Formatting Formating For Numbers number format Ereg Eregi Preg_match Preg Match keywords: ereg eregi preg_match preg match Syntax: preg_replace( $pattern, $replacement, $subject, $limit, $count ) Return Value: This function returns an array if the subject parameter is an array, or a string otherwise. Example: In this example we use preg_replace to remove non-numeric characters from a string, leaving only the numbers. It then prints the extracted numbers from the string. // PHP program to illustrate // preg_replace function // Declare a variable and initialize it $geeks = 'Welcome 2 Geeks 4 Geeks.'; // Filter the Numbers from String $int_var = preg_replace('/[^0-9]/', '', $geeks); // print output of function echo("The numbers are: $int_var n"); ?> Output The numbers are: 24 =========================================== filter_var You can use filter_var and sanitize the string to only include integers. $s = "Lesson 001: Complete"; echo filter_var($s, FILTER_SANITIZE_NUMBER_INT); ========================================== $s = "Lesson 001: Complete"; preg_match("/([0-9]+)/", $s, $matches); echo $matches[1]; ========================================== number_format (1234.567); //Returns the number 1,235 number_format (1234.567, 2); //Returns the number 1,234.57 number_format (1234.567, 2, ',', ' '); //Returns the number 1 234,57 number_format (1234.567, 1, 'a', 'b'); //Returns the number 1b234a6 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 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 Date Getdate date breakdown getdate (PHP 3, PHP 4 ) getdate -- Get date/time information Description array getdate ( [int timestamp]) Returns an associative array containing the date information of the timestamp, or the current local time if no timestamp is given, as the following associative array elements: Table 1. Key elements of the returned associative array Key Description Example returned values "seconds" Numeric representation of seconds 0 to 59 "minutes" Numeric representation of minutes 0 to 59 "hours" Numeric representation of hours 0 to 23 "mday" Numeric representation of the day of the month 1 to 31 "wday" Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday) "mon" Numeric representation of a month 1 through 12 "year" A full numeric representation of a year, 4 digits Examples: 1999 or 2003 "yday" Numeric representation of the day of the year 0 through 366 "weekday" A full textual representation of the day of the week Sunday through Saturday "month" A full textual representation of a month, such as January or March January through December 0 Seconds since the Unix Epoch, similar to the values returned by time() and used by date(). System Dependent, typically -2147483648 through 2147483647. Example 1. getdate() example The output will look similar to: Array ( [seconds] => 40 [minutes] => 58 [hours] => 21 [mday] => 17 [wday] => 2 [mon] => 6 [year] => 2003 [yday] => 167 [weekday] => Tuesday [month] => June [0] => 1055901520 ) Php 2 09/09/2023 Php Files Getting A Files Extension file extension File Management In PHP, there are several methods to retrieve the file extension from a given filename or path. 1. Using pathinfo(): The pathinfo() function is a versatile function that can extract various components of a file path, including the extension. Code 2. Using SplFileInfo::getExtension(): For object-oriented file handling, the SplFileInfo class provides the getExtension() method. Code getExtension(); echo $extension; // Outputs: jpg ?> 3. Using DirectoryIterator::getExtension(): When iterating through a directory, DirectoryIterator objects also offer the getExtension() method for individual files. Code isFile()) { echo $fileinfo->getFilename() . " extension: " . $fileinfo->getExtension() . "n"; } } ?> Note: If a file does not have an extension, these methods will typically return an empty string. If the filename starts with a dot (e.g., .htaccess), the characters following the dot will be considered the extension. Php 0 11/20/2025 Php Database Group By group by inner join SELECT category,categories.categoryid, COUNT(ads.categoryid) AS junk FROM categories LEFT JOIN ads ON categories.categoryid=ads.categoryid GROUP BY category ORDER BY category SELECT products.productname, soldout, restock, count( orderedproducts.productid ) FROM categories, products, orderedproducts, orders WHERE filled = 'Y' AND orders.orderid = orderedproducts.orderid AND orderedproducts.productid = products.productid AND categories.catid = products.catid AND orders.date>='2010-04-01' AND orders.date<='2010-04-30' GROUP BY productname SELECT * FROM `orderedproducts INNER JOIN orders ON orders.orderid=orderedproducts.orderid WHERE orders.date>='2010-04-01' AND orders.date<='2010-04-30' 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 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 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 Database Insert Table insert table DROP TABLE IF EXISTS `renters`; CREATE TABLE IF NOT EXISTS `renters` ( `renterid` mediumint(5) NOT NULL AUTO_INCREMENT, `last_name` varchar(50) NOT NULL DEFAULT '', `first_name` varchar(50) NOT NULL DEFAULT '', `address` varchar(50) NOT NULL DEFAULT '', `city` varchar(25) NOT NULL DEFAULT '', `zipcode` varchar(10) NOT NULL DEFAULT '', `phone` varchar(20) NOT NULL DEFAULT '', `cellphone` varchar(20) NOT NULL DEFAULT '', `email` varchar(100) NOT NULL DEFAULT '', `birthday` date NOT NULL DEFAULT '0000-00-00', `username` varchar(20) NOT NULL DEFAULT '', `password` varchar(20) NOT NULL DEFAULT '', `lastlogin` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', `logintimes` tinyint(4) NOT NULL DEFAULT '0', `level` tinyint(2) NOT NULL DEFAULT '0', PRIMARY KEY (`renterid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; // ============== EXAMPLE 2 ============================= $query="CREATE TABLE Reply ( replyid int PRIMARY KEY auto_increment, questionid int NOT NULL, reply text NOT NULL )"; $result = mysql_query($query);//run query if ($result) echo 'Question Table is Done/n'; Php 2 09/09/2023 Php Database Insert Using Select insert select INSERT INTO exportregistration( `registrationid` , `groupid` , `event` , `dateof` , `lastname` , `firstname` , `address` , `city` , `state` , `zip` , `home_phone` , `email` , `special_email` , `relationid` , `arrived` ) SELECT `registrationid` , `groupid` , `event` , `date` , `lastname` , `firstname` , `address` , `city` , `state` , `zip` , `home_phone` , `email` , `special_email` , `relationid` , `arrived` FROM EVENTS INNER JOIN event_registration ON events.eventid = event_registration.eventid ORDER BY date, lastname, firstname Php 2 09/09/2023 Php Database Inserting Multiple Rows Into A Table insert multiple records Database Inserting Multiple Rows into a Table One can also insert multiple rows into a table with a single insert query at once. To do this, include multiple lists of column values within the INSERT INTO statement, where column values for each row must be enclosed within parentheses and separated by a comma. Creating table using MySQLi Object-oriented Procedure : connect_error); } $sql = "INSERT INTO mytable (first_name, last_name, age) VALUES('raj', 'sharma', '15'), ('kapil', 'verma', '42'), ('monty', 'singh', '29'), ('arjun', 'patel', '32') "; if ($mysqli->query($sql) == = true) { echo "Records inserted successfully."; } else { echo "ERROR: Could not able to execute $sql. " .$mysqli->error; } $mysqli->close(); ? > Php 0 12/04/2023 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 Files Making An Image Viewer files images viewer Sometimes i have pictures that people want to view but are too numerous or inconvenient to email. I just do a batch conversion on the images (I use Irfan view a free app) and upload them to a new folder I called "stylists". Using this script in an index.php, I dump it with the pictures. It will show them in your browser. [Create image viewer] $imagedirectory="../stylists/"; $dir = opendir($imagedirectory); while ($file = readdir($dir)){ //for ($i=1; $i<=500; $i++){ // $file = readdir($dir); $fullpath=$current_dir.$file; echo "$file"; } closedir($dir); ?> You can tweak it to your folder requirements Php 752 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 Date Mktime - Create New Date build date new date int mktime ( [int $hour [, int $minute [, int $second [, int $month [, int $day [, int $year [, int $is_dst]]]]]]] ) $tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y")); $lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y")); $nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1) Php 2 09/09/2023 Php Language Number Type integer pow(5, 3) (float)$val (int)$val Php 2 09/09/2023 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 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 Formatting Physically Resize An Image resize image /* * File: SimpleImage.php * Author: Simon Jarvis * Copyright: 2006 Simon Jarvis * Date: 08/11/06 * Link: http://www.white-hat-web-design.co.uk/articles/php-image-resizing.php * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details: * http://www.gnu.org/licenses/gpl.html * */ class SimpleImage { var $image; var $image_type; function load($filename) { $image_info = getimagesize($filename); $this->image_type = $image_info[2]; if( $this->image_type == IMAGETYPE_JPEG ) { $this->image = imagecreatefromjpeg($filename); } elseif( $this->image_type == IMAGETYPE_GIF ) { $this->image = imagecreatefromgif($filename); } elseif( $this->image_type == IMAGETYPE_PNG ) { $this->image = imagecreatefrompng($filename); } } function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image,$filename,$compression); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image,$filename); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image,$filename); } if( $permissions != null) { chmod($filename,$permissions); } } function output($image_type=IMAGETYPE_JPEG) { if( $image_type == IMAGETYPE_JPEG ) { imagejpeg($this->image); } elseif( $image_type == IMAGETYPE_GIF ) { imagegif($this->image); } elseif( $image_type == IMAGETYPE_PNG ) { imagepng($this->image); } } function getWidth() { return imagesx($this->image); } function getHeight() { return imagesy($this->image); } function resizeToHeight($height) { $ratio = $height / $this->getHeight(); $width = $this->getWidth() * $ratio; $this->resize($width,$height); } function resizeToWidth($width) { $ratio = $width / $this->getWidth(); $height = $this->getheight() * $ratio; $this->resize($width,$height); } function scale($scale) { $width = $this->getWidth() * $scale/100; $height = $this->getheight() * $scale/100; $this->resize($width,$height); } function resize($width,$height) { $new_image = imagecreatetruecolor($width, $height); imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight()); $this->image = $new_image; } } ?> ============ Save the above file as SimpleImage.php and take a look at the following examples of how to use the script. The first example below will load a file named picture.jpg resize it to 250 pixels wide and 400 pixels high and resave it as picture2.jpg include('SimpleImage.php'); $image = new SimpleImage(); $image->load('picture.jpg'); $image->resize(250,400); $image->save('picture2.jpg'); ?> If you want to resize to a specifed width but keep the dimensions ratio the same then the script can work out the required height for you, just use the resizeToWidth function. include('SimpleImage.php'); $image = new SimpleImage(); $image->load('picture.jpg'); $image->resizeToWidth(250); $image->save('picture2.jpg'); ?> You may wish to scale an image to a specified percentage like the following which will resize the image to 50% of its original width and height include('SimpleImage.php'); $image = new SimpleImage(); $image->load('picture.jpg'); $image->scale(50); $image->save('picture2.jpg'); ?> You can of course do more than one thing at once. The following example will create two new images with heights of 200 pixels and 500 pixels include('SimpleImage.php'); $image = new SimpleImage(); $image->load('picture.jpg'); $image->resizeToHeight(500); $image->save('picture2.jpg'); $image->resizeToHeight(200); $image->save('picture3.jpg'); ?> The output function lets you output the image straight to the browser without having to save the file. Its useful for on the fly thumbnail generation header('Content-Type: image/jpeg'); include('SimpleImage.php'); $image = new SimpleImage(); $image->load('picture.jpg'); $image->resizeToWidth(150); $image->output(); ?> The following example will resize and save an image which has been uploaded via a form if( isset($_POST['submit']) ) { include('SimpleImage.php'); $image = new SimpleImage(); $image->load($_FILES['uploaded_image']['tmp_name']); $image->resizeToWidth(150); $image->output(); } else { ?> } ?> Php 1189 09/09/2023 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 Formatting Preparing Url For Passing With Php url encoding encode special characters Special characters such as spaces will mess up a url to the point where it will not work. PHP has these functions to handle this. Your will need to apply for each parameter passed or the "&" sign will be replaced for passing $_GETS rawurlencode() urlencode($var1) and urldecode($var1) //return the information into a readable format Php 808 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