https://www.php.net/
Assign range of number to array Easier way:
1 2 $foo = range (1 , 5 );print_r ($foo );
Harder way:
1 2 $foo = array ();for ($i = 1 ; $i <= 5 ; $i ++) $foo [] = $i ;
both will output:
1 2 3 4 5 6 7 8 Array ( [0 ] => 1 [1 ] => 2 [2 ] => 3 [3 ] => 4 [4 ] => 5 )
Reference:
Move a file in server 1 2 3 4 var $source = '/source/path/to/your/file.jpg' ;var $destination = '/destination/path/to/your/file.jpg' ;rename ($source , $destination );
Reference:
1 2 $path = '/path/to/your/dir' ;mkdir ($path , 0777 , true );
The 3rd argument is allowed to create intermediate directory.
Reference:
Get client located country info We make use of hostip.info api to get the location details.
1 2 3 4 5 6 7 8 9 10 11 $url = 'http://api.hostip.info/get_json.php?ip=' . $_SERVER ['REMOTE_ADDR' ];$ch = curl_init ();curl_setopt ($ch , CURLOPT_URL, $url );ob_start ();curl_exec ($ch );$content = ob_get_contents ();ob_end_clean ();curl_close ($ch );$result = json_decode ($content );
Get the date x
days before 1 2 3 4 5 6 function getPreviousDateFromDate ($date , $days_ago ) { return date ('Y-m-d' , strtotime ($date . ' -' . $days_ago . ' days' )); }
Inner function to access outer function’s variable 1 2 3 4 5 6 7 8 function outer ($foo ) { $inner = function ( ) use ($foo ) { echo $foo ; } $inner (); }
the use
keyword is to let the inner function to access the outer function’s variable
Reference:
Convert array to query string 1 2 3 4 5 6 7 $params = array ( 'p1' => 'value1' , 'p2' => 'value2' , ); $query_string = http_build_query ($params );echo $query_string ;
Reference:
Removed attributes accept href 1 2 3 4 5 6 7 <?php $html = 'This is a <a id="lnk" href="http://www.google.com" id="lnk">Google link</a> for you.' . ' This is another <a id="lnk" href="http://www.facebook.com">Facebook link</a> for you' ; $new_content = preg_replace ('/<a\s[^>]*href=\"([^\"]*)\"[^>]*>(.*)<\/a>/siU' , '<a href="$1">$2</a>' , $html );echo $new_content ;
The result will be
1 This is a <a href="http://www.google.com" >Google link</a > for you. This is another <a href="http://www.facebook.com" >Facebook link</a > for you
Reference:
Check whether is POST request 1 2 3 4 <?php function is_post ( ) { return $_SERVER ['REQUEST_METHOD' ] === 'POST' ; }
Reference:
URL from text (href) 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?php function url_from_text ($text ) { $reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/" ; $text = "The text you want to filter goes here. http://google.com" ; if (preg_match ($reg_exUrl , $text , $url )) { return preg_replace ($reg_exUrl , '<a href="' . $url [0 ] . '">' . $url [0 ] . '</a>' , $text ); } else { return $text ; } }
Reference:
Get last month date range 1 2 $first_day_prev_month = date ('Y-m-1' , strtotime ('first day of previous month' ));$last_day_prev_month = date ('Y-m-t' , strtotime ('first day of previous month' ));
Reference:
fgetcsv
read all as ONE lineThis is due to End-of-Line (EOL) problem in different environment (Windows is different from UNIX)
The EOL in Windows is ^M
, you can see this if you try to open via VIM.
1 2 3 while (($data = fgetcsv ($handle , 10000 )) !== FALSE ) { print_r ($data ); }
If you read the file which contains of ^M
character, then everything will be in a single line.
In order to solve this, add this before the while
statement
1 ini_set ('auto_detect_line_endings' , true );
Reference:
Loop through dates 1 2 3 4 5 6 7 8 9 $start_date = '2013-12-06' ;$end_date = '2014-04-20' ;while (strtotime ($start_date ) <= strtotime ($end_date )) { echo "$start_date \n" ; $start_date = date ('Y-m-d' , strtotime ('+1 day' , strtotime ($start_date ))); }
Reference:
Get image type 1 2 3 4 5 6 7 8 9 10 switch (exif_imagetype ('image/foo.jpg' )) { case IMAGETYPE_JPEG: echo 'JPEG' ; break ; case IMAGETYPE_PNG: echo 'JPEG' ; break ; ... }
Reference:
Insert a string into another string 1 2 3 4 5 6 $str = 'abc123' ;$result = substr_replace ($str , '-' , 3 , 0 );echo $result ;
Reference:
e.g. Format a date with dd/mm/yyyy
to yyyy-mm-dd
1 2 3 4 5 6 7 $date = '31/08/1987' ;$pattern = '/^(\d{2})\/(\d{2})\/(\d{4})$/' ;$replacement = '$3-$2-$1' ;$formatted_date = preg_replace ($pattern , $replacement , $date );echo $formatted_date ;
Output:
(\d{2})
- the braces is to keep a reference that can use it later (i.e. $1
) . Where \d
is to match integer only and {2}
is exactly 2 characters
\/
- because the slash (/) is a special character, so have to use backslash (\) to escape it
$3-$2-$1
- is the sequence of the submatch (i.e. (\d{2})
those inside the braces)
Reference:
iPad photo orientation issue by rotate image manually 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 function resample ($jpgFile , $thumbFile , $width , $orientation ) { list ($width_orig , $height_orig ) = getimagesize ($jpgFile ); $height = (int ) (($width / $width_orig ) * $height_orig ); $image_p = imagecreatetruecolor ($width , $height ); $image = imagecreatefromjpeg ($jpgFile ); imagecopyresampled ($image_p , $image , 0 , 0 , 0 , 0 , $width , $height , $width_orig , $height_orig ); switch ($orientation ) { case 3 : $image_p = imagerotate ($image_p , 180 , 0 ); break ; case 6 : $image_p = imagerotate ($image_p , -90 , 0 ); break ; case 8 : $image_p = imagerotate ($image_p , 90 , 0 ); break ; } imagejpeg ($image_p , $thumbFile , 90 ); }
Reference:
1 str_replace (' ' , ' ' , strip_tags ($description ));
Replace new line character with 1 $new_text = str_replace (array ("\r" , "\r\n" , "\n" ), ' ' , $text );
Reference:
Regex match any characters INCLUDING 1 2 3 4 5 6 7 8 9 10 11 12 $content = <<<EOD <html> <title>Test</title> <body> <div id="some-div"> Some text here </div> </body> </html> EOD ;$pattern = '/<body.*>(.*)<\/body>/s' ; preg_match ($pattern , $content , $result );
$result[0]
will give you
1 2 3 <div id ="some-div" > Some text here </div >
Reference:
Receive json
value from HTTP POST This will show nothing
In order to get the value
1 2 3 4 5 6 $json = file_get_contents ('php://input' );if ($json ) { $post = json_decode ($json , true ); } print_r ($post );
Reference:
Error on mysqli The error message was No such file or directory
Solution simply change the host to 127.0.0.1
instead of localhost
Reference:
Save web image into file 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 function save_image ($url , $dest_path ) { $ext = pathinfo ($url , PATHINFO_EXTENSION); $filename = str_replace (array ('0.' , ' ' ), array ('' , '' ), microtime ()) . '.' . $ext ; $ch = curl_init ($url ); $fp = fopen ($dest_path .'/' .ltrim ($filename , '/' ), 'wb' ); curl_setopt ($ch , CURLOPT_FILE, $fp ); curl_setopt ($ch , CURLOPT_HEADER, 0 ); curl_exec ($ch ); curl_close ($ch ); fclose ($fp ); return $filename ; }
References:
Regex validation for color code hex 1 2 3 4 if (preg_match ('/^#?([a-f0-9]{6}|[a-f0-9]{3})$/' , $hex )){ }
The regex above check the optional hash (#) and accept either 3 or 6 characters.
Reference:
Updated all null
to empty string in an array 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 function null_to_empty_str ($obj ) { $new_json_array = array (); foreach ($obj as $k => $v ) { if (is_array ($v )) { $new_json_array [$k ] = null_to_empty_str ($v ); continue ; } if ($v === null ) { $new_json_array [$k ] = '' ; continue ; } $new_json_array [$k ] = $v ; } return $new_json_array ; }
phpMyAdmin auto login Edit the file config.inc.php
1 2 3 4 5 $cfg ['Servers' ][$i ]['auth_type' ] = 'config' ;$cfg ['Servers' ][$i ]['user' ] = 'root' ;$cfg ['Servers' ][$i ]['password' ] = 'root_pass' ;
Reference:
Make use of array_map
to create key-value array 1 2 3 4 5 6 7 8 9 10 11 $original = [ 0 => ['id' => 'js' , 'name' => 'foo' ], 1 => ['id' => 'lim' , 'name' => 'bar' ], ]; $options = [];array_map (function($obj ) use (&$options ) { $options [$obj ['id ']] = $obj ['name ']; }, $original ); print_r ($options );
Result will be:
1 2 3 4 Array ( 'js' => 'foo' , 'lim' => 'bar' , )
Reference:
Call static method by dynamic class 1 2 3 <?php $class_name = 'FooBar' ;$class_name ::callMethod ($arg1 ...);
If want to initialize
1 2 <?php $obj = new $class_name ();
Replace html tag by regex Let say replace <a>
to <em>
1 2 3 <?php $html = '<strong>No 1.</strong> This is a <a href="...">Link</a>' ;preg_replace_callback ('(<a.*>(.*?)</a>)' , function($a ) {return '<em>' . $a [1 ] . '</em>' );}, $html );
Reference:
Call dynamic class static function 1 2 3 <?php $class_name = 'Helpers\DateHelper' ;$result = call_user_func ($class_name . '::convert' , '2018-04-30' , 'M d, Y' );
This is equivalent to Helpers\DateHelper::convert('2018-04-30', 'M d, Y')
Reference:
DOMDocument Using this with Symfony DomCrawler .
Append new element 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 <?php use Symfony \Component \DomCrawler \Crawler as DomCrawler ;$html = ....;$doc = new \DOMDocument ;$doc ->loadHtml ($html );$crawler = new DomCrawler ($doc );$row_nodes = $crawler ->filter ('.rows' );foreach ($row_nodes as $node ) { $div_col = $doc ->createElement ('div' ); $div_col ->setAttribute ('class' , 'col-md-12' ); $div_col ->textContent = 'This is the inner html content' ; $node ->appendChild ($div_col ); } echo $crawler ->html ();
Reference:
Facebook Initialize the facebook object 1 2 3 4 $facebook = new Facebook (array ( 'appId' => '<your app id here>' , 'secret' => '<your app secret here>' , ));
Get current user’s allowed permission 1 2 $permissions = $facebook ->api ('/me/permissions' );print_r ($permissions );
Get current user’s info 1 $user = $facebook ->api ('/me' );
TCPDF Align height of HTML table row Adjust the line-height
& font-size
, otherwise it won’t work.
Example
1 2 3 4 5 <table cellpadding ="0" > <tr style ="line-height: 5px; font-size: 4px;" > <td > Your content here</td > </tr > </table >
NOTE: margin & padding properties won’t work here
WideImage Resize image proportionally by height Example shows resize the image to any width but exactly 100px height
1 2 $img = WideImage ::load ('/path/to/image.jpg' );$img ->resize ($img ->getWidth (), 100 )->saveToFile ('/destination/image.jpg' );
Set the width to original image size will achieve this.
Create empty image from text 1 2 3 4 5 6 7 8 9 10 11 12 $wideImage = \WideImage_TrueColorImage ::create (100 , 100 );$wideImage ->fill (0 ,0 , $wideImage ->getTransparentColor ());$canvas = $wideImage ->getCanvas ();$canvas ->useFont ('/path/to/fonts/Helvetica-Bold.otf' , 30 , $wideImage ->allocateColor (255 , 255 , 255 ));$canvas ->writeText ('center' , 'center' , 'Your text goes here' );$wideImage ->saveToFile ('output.png' );
Reference: