PHP Practical code fragment must be collected _php tips

Source: Internet
Author: User
Tags abs cos explode flush fread sin strlen svn

It's always good to have a magic tool when writing code! Here's a collection of 40+ PHP snippets that can help you develop PHP projects. We have already shared the 23 PHP code snippets that must be collected.
These PHP snippets are also very helpful to PHP beginners, very easy to learn, let's start to learn it ~

24. Create a CSV file from PHP data

function Generatecsv ($data, $delimiter = ', ', $enclosure = ' "') {
  $handle = fopen (' php://temp ', ' r+ ');
  foreach ($data as $line) {
      fputcsv ($handle, $line, $delimiter, $enclosure);
  Rewind ($handle);
  while (!feof ($handle)) {
      $contents. = Fread ($handle, 8192);
  }
  Fclose ($handle);
  return $contents;
}
  

Grammar:

<?php
$data [0] = "apple";
$data [1] = "oranges";
Generatecsv ($data, $delimiter = ', ', $enclosure = ' ");
? >

25. Parsing XML Data

$xml _string= "<?xml version= ' 1.0 '?>
<moleculedb>
  <molecule name= ' benzine ' >
    < symbol>ben</symbol>
    <code>A</code>
  </molecule>
  <molecule name= ' Water ' >
    <symbol>h2o</symbol>
    <code>K</code>
  </molecule>
</ Moleculedb> ";
   
The load the XML string using SimpleXML function
$xml = simplexml_load_string ($xml _string);
   
Loop through the each node of molecule
foreach ($xml->molecule as $record)
{
  //attribute are accesste D
  by Echo $record [' name '], ';
  Node are accessted by-> operator
  Echo $record->symbol, ';
  echo $record->code, ';
}

26. Parse JSON Data

$json _string= ' {"id": 1, "name": "Rolf", "Country": "Russia", "office": ["Google", "Oracle"]} ';
$obj =json_decode ($json _string);
Print the parsed data
echo $obj->name;//displays Rolf
echo $obj->office[0];//displays Google



27. Get the current page URL
This PHP fragment can help you get the user to log in and jump directly to the previous page

function Current_url ()
{
$url = "http://". $_server[' http_host '. $_server[' Request_uri '];
$validURL = Str_replace ("&", "&", $url);
return validurl;
}

Grammar:

<?php
echo "Currently you are on:". Current_url ();
? >

28. Get the latest tweets from any Twitter account

function My_twitter ($username)
{
   $no _of_tweets = 1;
   $feed = "Http://search.twitter.com/search.atom?q=from:". $username. "&rpp=". $no _of_tweets;
   $xml = Simplexml_load_file ($feed);
  foreach ($xml->children () as $child) {
    foreach ($child as $value) {
      if ($value->getname () = = "link") $link = $ value[' href '];
      if ($value->getname () = "Content") {
        $content = $value. "";
    Echo ' <p class= ' twit > '. $content. ' <a class= ' TWT ' href= '. $link. ' title= ' "> </a></p> ';
      }  
    }
  }  
}  

Grammar:

<?php
$handle = "Koonktech";
My_twitter ($handle);
? >

29. Forwarding Quantity
Use this PHP fragment to detect how many forwarding numbers your page URLs have

function Tweetcount ($url) {
  $content = file_get_contents ("http://api.tweetmeme.com/url_info?url=". $url);
  $element = new SimpleXMLElement ($content);
  $retweets = $element->story->url_count;
  if ($retweets) {return
    $retweets;}
  else {return
    0;
}}
  

Grammar:

<?php
$url = "http://blog.koonk.com";
$count = Tweetcount ($url);
return $count;
? >

30. Calculate the difference of two dates

<?php $date 1 = date (' y-m-d ');
$date 2 = "2015-12-04";
$diff = ABS (Strtotime ($date 2)-Strtotime ($date 1));
$years = Floor ($diff/(365*60*60*24));
$months = Floor (($diff-$years * 365*60*60*24)/(30*60*60*24));
$days = Floor (($diff-$years * 365*60*60*24-$months *30*60*60*24)/(60*60*24));
printf ("%d years,%d months,%d days\n", $years, $months, $days);
--------------------------------------------------------OR $date 1 = new DateTime ("2007-03-24");
$date 2 = new DateTime ("2009-06-26");
$interval = $date 1->diff ($date 2); echo "Difference". $interval->y. "Years," he said.
$interval->m. "Months," $interval->d. "Days"; Shows the total amount of days (not divided to years, months and days like above) echo "difference". $interval->days.
"Days"; --------------------------------------------------------OR/** * Calculate differences between two dates wit h precise semantics. Based on Phps DateTime::d iff () * implementation by Derick Rethans. Ported To PHP by Emil H, 2011-05-02.
 No rights reserved. * * for original code: * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/tm2unixtime.c?revision= 302890&view=markup * http://svn.php.net/viewvc/php/php-src/trunk/ext/date/lib/interval.c?revision=298973
    &view=markup/function _date_range_limit ($start, $end, $adj, $a, $b, $result) {if ($result [$a] < $start) {
    $result [$b]-= intval ($start-$result [$a]-1)/$adj) + 1;
  $result [$a] + + = $adj * Intval ($start-$result [$a]-1)/$adj + 1);
    } if ($result [$a] >= $end) {$result [$b] + + = intval ($result [$a]/$ADJ);
  $result [$a]-= $adj * Intval ($result [$a]/$ADJ);
return $result; function _date_range_limit_days ($base, $result) {$days _in_month_leap = array (31, 31, 29, 31, 30, 31, 30, 31, 31, 30,
  31, 30, 31);
  $days _in_month = Array (31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  _date_range_limit (1, N, "M", "Y", & $base);
  $year = $base ["Y"]; $month = $base ["M "];
      if (! $result ["invert"]) {while ($result ["D"] < 0) {$month-;
        if ($month < 1) {$month + = 12;
      $year--; } $leapyear = $year% 400 = 0 | |
      ($year%!= 0 && $year% 4 = 0); $days = $leapyear?
      $days _in_month_leap[$month]: $days _in_month[$month];
      $result ["D"] + = $days;
    $result ["M"]--; } else {while ($result ["D"] < 0) {$leapyear = $year% 400 = 0 | |
      ($year%!= 0 && $year% 4 = 0); $days = $leapyear?
      $days _in_month_leap[$month]: $days _in_month[$month];
      $result ["D"] + = $days;
      $result ["M"]--;
      $month + +;
        if ($month >) {$month-= 12;
      $year + +;
}} return $result;
  function _date_normalize ($base, $result) {$result = _date_range_limit (0, N, "s", "I", $result);
  $result = _date_range_limit (0, M, "I", "H", $result);
  $result = _date_range_limit (0, N, "H", "D", $result); $result = _daTe_range_limit (0, a, "M", "Y", $result);
  $result = _date_range_limit_days (& $base, & $result);
  $result = _date_range_limit (0, a, "M", "Y", $result);
return $result;
 }/** * accepts two UNIX timestamps.
  */function _date_diff ($one, $two) {$invert = false;
    if ($one > $two) {list ($one, $two) = Array ($two, $one);
  $invert = true;
  $key = Array ("Y", "M", "D", "H", "I", "s");
  $a = Array_combine ($key, Array_map ("Intval", Explode ("", Date ("Y m D H i S", $one)));
  $b = Array_combine ($key, Array_map ("Intval", Explode ("", Date ("Y m D H i S", $two)));
  $result = Array ();
  $result ["y"] = $b ["y"]-$a ["Y"];
  $result ["M"] = $b ["M"]-$a ["M"];
  $result ["d"] = $b ["D"]-$a ["D"];
  $result ["h"] = $b ["h"]-$a ["H"];
  $result ["i"] = $b ["i"]-$a ["I"];
  $result ["s"] = $b ["s"]-$a ["s"]; $result ["invert"] = $invert?
  1:0;
  $result ["days"] = Intval (ABS ($one-$two)/86400);
  if ($invert) {_date_normalize (& $a, & $result);
} else {    _date_normalize (& $b, & $result);
return $result;
} $date = "2014-12-04 19:37:22";
Echo ' <pre> ';
Print_r (_date_diff (Strtotime ($date), Time ()));
 Echo ' </pre> ';?>

31. Delete Folder Contents

The 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'll deletes images folder along with its contents.
>

32. Search and Highlight keywords in the string

function Highlighter_text ($text, $words)
{
  $split _words = Explode ("", $words);
  foreach ($split _words as $word)
  {
    $color = "#4285F4";
    $text = Preg_replace ("| $word) | Ui ",
      " <span style=\ "color:". $color. "; \" ><b>$1</b></span> ", $text);
  }
  return $text;
}

Grammar:

<?php
$string = "I like chocolates and I like apples";
$words = "Apple";
Echo Highlighter_text ($string, $words);
>

33. Write to File

?
$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

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 = "Yun_qi_img/logo.png";
$rename = "Koonk.png";
Imagefromurl ($url, $rename);
>

35. Detection URL is valid

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 URL is valid.
? >

36. Generate two dimensional code

function Qr_code ($data, $type = "TXT", $size = ' m ', $ec = ' L ', $margin = ' 0 ') 
{
   $types = array ("URL" =-->) http:// "," tel "=>" Tel: "," TXT "=>" "," EMAIL "=>" 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 two map coordinates

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 * 1000;
  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).
>

38. Get all Tweets for a specific topic label

 function gettweets ($hash _tag) {$url = ' http://search.twitter.com/search.atom?q= '. Urle
  Ncode ($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 the response from Twitter, uncomment this next part out://echo "<p>Response:</p>"; echo "<pre>". Htmlspecialchars ($xml). "
  </pre> ";
  $affected = 0;
  $twelement = new SimpleXMLElement ($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 suffix for numbers

Friday the 13th
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 = ten;
echo ordinal ($number); Output is 10th
?>

40. Limit the speed of file downloads

<?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 browser print fread ($file, round ($download _rate * 10  
  
    24));
  
    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 Picture

<?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 size of the remote file

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 '. Base64_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 = "Yun_qi_img/logo.png";
$size = Remote_filesize ($url);
echo $size;
? >

43. Using Imagebrick for PDF to image conversion

<?php
$pdf _file  = './pdf/demo.pdf ';
$save _to  = './jpg/demo.jpg ';   Make sure so Apache has permissions to write in this folder! (Common problem)
Execute ImageMagick command ' convert ' and convert PDF to JPG with applied settings
exec (' Convert '. $pdf _file. ' "-co Lorspace 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." $output;
? >

44. Use TinyURL to generate short URLs

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 midwife Builder
Use the following PHP snippet to get your users to download Youtube videos

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\ "&GT;HQ flv (if available) &Lt;/a>\n\t\t ";
  echo "<a href=\" $mp 4_link\ ">mp4</a>\n\t\t";
echo "<a href=\" $THREEGP _link\ ">3gp</a>\n";
 }

-Facebook-style timestamp

 Facebook (x mins age, Y hours ago etc) 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 future date or past date if ($now > $unix _date) {$difference = $now-$unix _date;
      
  $tense = "Ago";
    else {$difference = $unix _date-$now;
  $tense = "From now"; for ($j = 0; $difference >= $lengths [$j] && $j < count ($lengths)-1; $j + +) {$difference/= $leng
  ths[$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 the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.