31. Delete Folder Contents
[Code]php Code:
function Delete ($path) { if (is_dir ($path) = = = True) { $files = Array_diff (Scandir ($path), Array ('. ', '. ')); foreach ($files as $file) { Delete (Realpath ($path). '/' . $file); } return rmdir ($path); } else if (is_file ($path) = = = True) { return unlink ($path); } return false;}
Grammar:
<?php
$path = "images/";
Delete ($path); This would delete images folder along with its contents.
?>
32. Search and Highlight keywords in a string
[Code]php Code:
function Highlighter_text ($text, $words) { $split _words = Explode ("", $words); foreach ($split _words as $word) { $color = "#4285F4"; $text = Preg_replace ("| ( $word) | Ui ", " <b>$1</b> ", $text); } return $text;}
Grammar:
<?php
$string = "I like chocolates and I like apples";
$words = "Apple";
Echo Highlighter_text ($string, $words);
?>
33. Writing Files
<?
$filename = ' blog.csv ';
$fp = fopen ($filename, ' w ');
$output = "Hello";
$output. = "world!";
$output. = "\ r \ n";
Fputs ($fp, $output);
Fclose ($FP);
?>
34. Download the picture according to the URL
[Code]php Code:
function Imagefromurl ($image, $rename) {$ch = Curl_init ($image); curl_setopt ($ch, Curlopt_header, 0); curl_setopt ($ch, Curlopt_returntransfer, 1); curl_setopt ($ch, curlopt_binarytransfer,1), $rawdata =curl_exec ($ch); Curl_close ($ch); $ fp = fopen ("$rename", ' W '); fwrite ($fp, $rawdata); Fclose ($FP);}
Grammar:
<?php
$url = "Http://koonk.com/images/logo.png";
$rename = "Koonk.png";
Imagefromurl ($url, $rename);
?>
35. Detect if the URL is valid
[Code]php Code:
function Isvalidurl ($url) {$check = 0;if (Filter_var ($url, Filter_validate_url)!== false) { $check = 1;} return $check;}
Grammar:
<?php
$url = "http://koonk.com";
$check = Checkvalidurl ($url);
Echo $check; If returns 1 then URLs is valid.
?>
36. Generate two-dimensional code
[Code]php Code:
function Qr_code ($data, $type = "TXT", $size = ' Max ', $ec = ' L ', $margin = ' 0 ') { $types = array ("URL" =--> "HTTP +/ "," tel "and" Tel: "," TXT "=" "," EMAIL "and" MAILTO: "); if (!in_array ($type, Array ("URL", "TEL", "txt", "EMAIL")))) { $type = "txt"; } if (!preg_match ('/^ '. $types [$type]. ' /', $data)) { $data = str_replace ("\ \", "", $types [$type]). $data; } $ch = Curl_init (); $data = UrlEncode ($data); curl_setopt ($ch, Curlopt_url, ' Http://chart.apis.google.com/chart '); curl_setopt ($ch, Curlopt_post, true); curl_setopt ($ch, Curlopt_postfields, ' chs= '. $size. ' x '. $size. ' &cht=qr&chld= '. $ec. ' | '. $margin. ' &chl= '. $data); curl_setopt ($ch, Curlopt_returntransfer, true); curl_setopt ($ch, Curlopt_header, false); curl_setopt ($ch, Curlopt_timeout,); $response = curl_exec ($ch); Curl_close ($ch); return $response;}
Grammar:
<?php
Header ("Content-type:image/png");
Echo Qr_code ("http://koonk.com", "URL");
?>
37. Calculate the distance between the two map coordinates
[Code]php Code:
function Getdistancebetweenpointsnew ($latitude 1, $longitude 1, $latitude 2, $longitude 2) { $theta = $longitude 1-$ Longitude2; $miles = (sin (Deg2rad ($latitude 1)) * Sin (Deg2rad ($latitude 2)) + (cos (Deg2rad ($latitude 1)) * cos (Deg2rad ($latitude 2)) * Cos (Deg2rad ($theta))); $miles = ACOs ($miles); $miles = Rad2deg ($miles); $miles = $miles * 1.1515; $feet = $miles * 5280; $yards = $feet/3; $kilometers = $miles * 1.609344; $meters = $kilometers *; Return compact (' Miles ', ' feet ', ' yards ', ' kilometers ', ' meters '); }
Grammar:
<?php
$point 1 = Array (' lat ' = = 40.770623, ' long ' =-73.964367);
$point 2 = Array (' lat ' = = 40.758224, ' long ' =-73.917404);
$distance = getdistancebetweenpointsnew ($point 1[' lat '), $point 1[' long '], $point 2[' lat '), $point 2[' long ']);
foreach ($distance as $unit = = $value) {
echo $unit. ': '. Number_format ($value, 4). ' <br/> ';
}
?>
38. Get all Tweets for a specific topic tag
[Code]php Code:
function Gettweets ($hash _tag) {$url = ' http://search.twitter.com/search.atom?q= '. UrlEncode ($hash _tag); echo "<p>connecting to <strong> $url </strong> ...</p>"; $ch = Curl_init ($url); curl_setopt ($ch, Curlopt_returntransfer, TRUE); $xml = curl_exec ($ch); Curl_close ($ch); If you want to see the response from Twitter, uncomment this next part out://echo "<p>Response:</p>"; echo "<pre>". Htmlspecialchars ($xml). " </pre> "; $affected = 0; $twelement = new <a href= "http://www.php-z.com/" target= "_blank" class= "Relatedlink" >Simple</a> XMLElement ($xml); foreach ($twelement->entry as $entry) {$text = Trim ($entry->title); $author = Trim ($entry->author->name); $time = Strtotime ($entry->published); $id = $entry->id; echo "<p>tweet from". $author. ": <strong>". $text. " </strong> <em>posted ". Date (' n/j/y g:i a ', $time)." </em≫</p> "; } return true;
39. Add Th,st,nd or Rd as the number suffix
Friday the 13th
[Code]php Code:
function ordinal ($CDNL) { $test _c = ABS ($CDNL)%; $ext = (ABS ($CDNL)%100 < && abs ($CDNL)%100 > 4)? ' th ' : (($test _c < 4)? ($test _c < 3)? ($test _c < 2)? ($test _c < 1) ? ' th ': ' st ': ' nd ': ' rd ': ' th '); return $CDNL. $ext; }
Grammar:
<?php
$number = 10;
echo ordinal ($number); Output is 10th
?>
40. Limit the speed of file downloads
[Code]php Code:
<!--? php//Local file that should is send to the Client$local_file = ' test-file.zip ';//filename that the user gets as Default$download_file = ' Your-download-name.zip '; Set the download rate limit (=--> 20,5 kb/s) $download _rate = 20.5; if (file_exists ($local _file) && is_file ($local _file)) {//Send Headers header (' cache-control:private '); Header (' Content-type:application/octet-stream '); Header (' Content-length: '. FileSize ($local _file)); Header (' content-disposition:filename= '. $download _file); Flush content flush (); Open file Stream $file = fopen ($local _file, "R"); while (!feof ($file)) {//Send the current file part to the browser print fread ($file, round ($download _rate * 1024)); Flush the content to the browser flush (); Sleep One Second sleep (1); }//Close file stream fclose ($file);} else {die (' error:the file '. $local _file. ' does not exist! ');}? >
41. Convert Text to Images
<?php
Header ("Content-type:image/png");
$string = $_get[' text '];
$im = Imagecreatefrompng ("Images/button.png");
$color = Imagecolorallocate ($im, 255, 255, 255);
$PX = (Imagesx ($im)-7.5 * strlen ($string))/2;
$py = 9;
$fontSize = 1;
Imagestring ($im, FontSize, $px, $py, $string, $color);
Imagepng ($im);
Imagedestroy ($im);
?>
42. Get the remote file size
[Code]php Code:
function Remote_filesize ($url, $user = "", $PW = "") { ob_start (); $ch = Curl_init ($url); curl_setopt ($ch, Curlopt_header, 1); curl_setopt ($ch, curlopt_nobody, 1); if (!empty ($user) &&!empty ($PW)) { $headers = array (' Authorization:basic '). <a href= "http://www.php-z.com/" target= "_blank" class= "Relatedlink" >base</a>64_encode ("$user: $PW")); curl_setopt ($ch, Curlopt_httpheader, $headers); } $ok = curl_exec ($ch); Curl_close ($ch); $head = Ob_get_contents (); Ob_end_clean (); $regex = '/content-length:\s ([0-9].+?) \s/'; $count = Preg_match ($regex, $head, $matches); return Isset ($matches [1])? $matches [1]: "Unknown";}
Grammar:
<?php
$file = "Http://koonk.com/images/logo.png";
$size = Remote_filesize ($url);
Echo $size;
?>
43. Convert PDF to image using Imagebrick
<?php
$pdf _file = './pdf/demo.pdf ';
$save _to = './jpg/demo.jpg '; Make sure that Apache have permissions to write on this folder! (Common problem)
Execute ImageMagick command ' convert ' and convert PDF to JPG with applied settings
EXEC (' Convert '. $pdf _file. ' "-colorspace rgb-resize" '. $save _to. ' "', $output, $return _var);
if ($return _var = = 0) {//if exec successfuly converted PDF to JPG
print "Conversion OK";
}
else print "Conversion failed.<br/>". $output;
?>
44. Generate Short URLs using TinyURL
[Code]php Code:
function Get_tiny_url ($url) { $ch = Curl_init (); $timeout = 5; curl_setopt ($ch, Curlopt_url, ' http://tinyurl.com/api-create.php?url= '. $url); curl_setopt ($ch, curlopt_returntransfer,1); curl_setopt ($ch, Curlopt_connecttimeout, $timeout); $data = curl_exec ($ch); Curl_close ($ch); return $data; }
Grammar:
<?php
$url = "Http://blog.koonk.com/2015/07/Hello-World";
$tinyurl = Get_tiny_url ($url);
Echo $tinyurl;
?>
YouTube Download Chain Builder
Use the PHP snippet below to get your users to download Youtube videos
[Code]php Code:
function Str_between ($string, $start, $end) {$string = "". $string; $ini = Strpos ($string, $start); if ($ini = = 0) return ""; $ini + = strlen ($start); $len = Strpos ($string, $end, $ini)-$ini; Return substr ($string, $ini, $len); }function Get_youtube_download_link () {$youtube _link = $_get[' YouTube '); $youtube _page = file_get_contents ($youtube _link); $v _id = Str_between ($youtube _page, "&video_id=", "&"); $t _id = Str_between ($youtube _page, "&t=", "&"); $flv _link = "http://www.youtube.com/get_video?video_id= $v _id&t= $t _id"; $HQ _flv_link = "http://www.youtube.com/get_video?video_id= $v _id&t= $t _id&fmt=6"; $MP 4_link = "http://www.youtube.com/get_video?video_id= $v _id&t= $t _id&fmt=18"; $THREEGP _link = "http://www.youtube.com/get_video?video_id= $v _id&t= $t _id&fmt=17"; echo "\t\tdownload (right-click > Save As): \n\t\t"; echo "<a href=" \ "$flv _link\" ">flv</a>\n\t\t"; echo "<a href=" \ "$hq _flv_link\" ">hq flv (if Available) </a>\n\t\t "; echo "<a href=" \ "$mp 4_link\" ">mp4</a>\n\t\t"; echo "<a href=" \ "$THREEGP _link\" ">3gp</a><br><br>\n";}
The time stamp of Facebook style
Facebook (x mins age, Y hours ago etc)
[Code]php Code:
function Nicetime ($date) {if (empty ($date)) {return "No date provided"; } $periods = Array ("Second", "Minute", "Hour", "Day", "Week", "Month", "year", "decade"); $lengths = Array ("60", "60", "24", "7", "4.35", "12", "10"); $now = time (); $unix _date = Strtotime ($date); Check validity of date if (empty ($unix _date)) {return "Bad date"; }//Is it the future date or past date if ($now > $unix _date) {$difference = $now-$unix _date; $tense = "Ago"; } else {$difference = $unix _date-$now; $tense = "from"; } for ($j = 0; $difference >= $lengths [$j] && $j < count ($lengths)-1; $j + +) {$difference/= $ lengths[$j]; } $difference = round ($difference); if ($difference! = 1) {$periods [$j].= "s"; } return "$difference $periods [$j] {$tense}";}
Grammar:
<?php
$date = "2015-07-05 03:45";
$result = Nicetime ($date); 2 days ago
?>
The above is 46 very useful PHP code fragment (three) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!