23 PHP Useful code snippets that must be collected, _php tutorial

Source: Internet
Author: User
Tags ziparchive ssl certificate

23 PHP Useful code snippets that must be collected,


It's always good to have a magical tool when writing code! Here is a collection of 40+ PHP code snippets to help you develop your PHP project.
These PHP snippets are also very helpful for beginners in PHP, so it's easy to learn, so let's start learning ~
1. Send SMS
When developing a Web or mobile app, you'll often encounter the need to send SMS to the user, either because of login reasons, or to send a message. The following PHP code implements the ability to send SMS.
In order to send SMS in any language, an SMS gateway is required. Most SMS will provide an API, here is the use of MSG91 as SMS gateway.

function Send_sms ($mobile, $msg) {$authKey = "xxxxxxxxxxx";d ate_default_timezone_set ("Asia/kolkata"); $date = Strftime      ("%y-%m-%d%h:%m:%s");//multiple mobiles numbers separated by comma$mobilenumber = $mobile;      Sender Id,while using route4 sender ID should be 6 characters long $senderId = "Ikoonk";      Your message to send, the ADD URL encoding here. $message = UrlEncode ($msg); Define Route$route = "template";//prepare you post Parameters$postdata = Array (' authkey ' = = $authKey, ' mobiles ' =& Gt      $mobileNumber, ' message ' and ' $message, ' sender ' and ' $senderId, ' route ' and ' $route ');      API url$url= "https://control.msg91.com/sendhttp.php";  init the resource$ch = Curl_init (); Curl_setopt_array ($ch, array (curlopt_url = $url, Curlopt_returntransfer =            True, Curlopt_post = true, Curlopt_postfields = $postData//,curlopt_followlocation = true)); Ignore SSL Certificate verificationcurl_setopt ($ch, curlopt_ssl_verifyhost, 0); Curl_setopt ($ch, Curlopt_ssl_verifypeer, 0);      Get response$output = curl_exec ($ch);//print error if Anyif (Curl_errno ($ch)) {echo ' ERROR: '. Curl_error ($ch);} Curl_close ($ch);}

where "$authKey =" xxxxxxxxxxx ";" Need you to enter your password, "$senderId =" Ikoonk ";" You are required to enter your SenderID. You need to specify the country code when you enter a mobile number (for example, the United States is 1, India is 91).
Grammar:

<?php$message = "Hello World"; $mobile = "918112998787"; Send_sms ($mobile, $message);? >

2. Send mail using Mandrill
The Mandrill is a powerful SMTP provider. Developers tend to use a third-party SMTP provider to get better delivery of their shipments.
In the following function, you need to put "mandrill.php" in the same folder as the PHP file so that you can use TA to send the message.

function Send_email ($to _email, $subject, $message 1) {require_once ' mandrill.php '; $apikey = ' xxxxxxxxxx ';//specify your API Key Here$mandrill = new Mandrill ($apikey);      $message = new StdClass (), $message->html = $message 1; $message->text = $message 1; $message->subject = $subject; $ Message->from_email = "blog@koonk.com";//sender email$message->from_name = "Koonk";//sender name$message-> to = Array ("e-mail" = $to _email)); $message->track_opens = true;      $response = $mandrill->messages->send ($message);}

$apikey = ' xxxxxxxxxx '; Specify your API key here "requires you to specify your API keys (obtained from the Mandrill account).
Grammar:

<?php$to = "abc@example.com"; $subject = "This is a test email"; $message = "Hello world!"; Send_email ($to, $subject, $message);? >

In order to achieve the best results, it is best to follow the Mandrill tutorial to configure DNS.

3. PHP function: Block SQL injection
SQL injection or SQLi common attack site means, use the code below to help you prevent these tools.

function Clean ($input) {  if (Is_array ($input))  {    foreach ($input as $key = = $val)     {      $output [$ Key] = clean ($val);      $output [$key] = $this->clean ($val);    }  }  else  {    $output = (string) $input;    If Magic quotes is on and use strip slashes    if (GET_MAGIC_QUOTES_GPC ())    {      $output = stripslashes ($OUTPU t);    }    $output = Strip_tags ($output);    $output = Htmlentities ($output, ent_quotes, ' UTF-8 ');  } Return the clean text  return $output;}

Grammar:

<?php$text = ""; $text = Clean ($text); Echo $text; >

4. Detecting User Locations
Use the following function to detect in which city the user visited your website

function Detect_city ($ip) {$default = ' UNKNOWN '; $curlopt _useragent = ' mozilla/5.0 (Windows; U Windows NT 5.1; En-us;              rv:1.9.2) gecko/20100115 firefox/3.6 (. NET CLR 3.5.30729) '; $url = ' http://ipinfodb.com/ip_locator.php?ip= '.    UrlEncode ($IP);              $ch = Curl_init (); $curl _opt = Array (curlopt_followlocation = 1, curlopt_header = 0, Curlopt_returntransfer = 1      , curlopt_useragent = $curlopt _useragent, Curlopt_url = $url, curlopt_timeout = 1, Curlopt_referer = '/http '.              $_server[' Http_host '],);              Curl_setopt_array ($ch, $curl _opt);              $content = curl_exec ($ch);    if (!is_null ($curl _info)) {$curl _info = Curl_getinfo ($ch);              } curl_close ($ch); if (Preg_match (' {
  • City: ([^<]*)
  • }i ', $content, $regs)) {$city = $regs [1]; } if (Preg_match (' {
  • State/province: ([^<]*)
  • }i ', $content, $regs)) {$state = $regs [1]; if ($city! = "&& $state! =") {$location = $city. ', ' . $state; return $location; }else{return $default; } }

    Grammar:

    <?php$ip = $_server[' remote_addr ']; $city = detect_city ($IP); Echo $city; >

    5. Get the source code for the Web page
    Use the following function to get the HTML code for any Web page

    function Display_sourcecode ($url) {$lines = file ($url); $output = ""; foreach ($lines as $line _num = + $line) {  //loop Thru each line and prepend line numbers  $output. = "Line #{$line _num} :". Htmlspecialchars ($line). "\ n";}}

    Grammar:

    <?php$url = "http://blog.koonk.com"; $source = Display_sourcecode ($url); Echo $source; >

    6. Calculate the users who like your Facebook page

    function Fb_fan_count ($facebook _name) {  $data = Json_decode (file_get_contents ("https://graph.facebook.com/"). $ Facebook_name));  $likes = $data->likes;  return $likes;}

    Grammar:

    <?php$page = "Koonktechnologies"; $count = Fb_fan_count ($page); Echo $count; >

    7. Determine the dominant color of any image

    function Dominant_color ($image) {$i = Imagecreatefromjpeg ($image); for ($x =0; $x
     
      
       
      >) & 0xFF;    $g  = ($rgb >> & 0xFF;    $b  = $rgb & 0xFF;    $rTotal + = $r;    $gTotal + = $g;    $bTotal + = $b;    $total + +;  }} $rAverage = Round ($rTotal/$total); $gAverage = round ($gTotal/$total); $bAverage = round ($bTotal/$total);}
     
      

    8. Whois query
    Use the following function to get the full details of any domain user

    function Whois_query ($domain) {//fix the domain name: $domain = Strtolower (Trim ($domain));  $domain = preg_replace ('/^http:\/\//i ', ' ', $domain);  $domain = preg_replace ('/^www\./i ', ' ', $domain);  $domain = explode ('/', $domain);       $domain = Trim ($domain [0]);  Split the TLD from domain name $_domain = explode ('. ', $domain);  $lst = count ($_domain)-1;       $ext = $_domain[$lst]; You find resources and lists//like these on Wikipedia:////Http://de.wikipedia.org/wiki/Whois//$servers = AR Ray ("Biz" = "whois.neulevel.biz", "com" = "whois.internic.net", "us" = "whois.nic.us", "Coop" =&G T     "Whois.nic.coop", "info" = "Whois.nic.info", "name" = "Whois.nic.name", "net" = "Whois.internic.net", "gov" = "whois.nic.gov", "edu" = "whois.internic.net", "mil" = "rs.internic.net", "int" and "WH" Ois.iana.org "," ac "=" whois.nic.ac "," ae "=" whois.uaenic.ae "," at "and" Whois.ripe.net ", "au" = "whois.aunic.net", "be" = "whois.dns.be", "bg" = "whois.ripe.net", "BR" and "Whois.regi" stro.br "," BZ "=" whois.belizenic.bz "," Ca "=" whois.cira.ca "," cc "=" whois.nic.cc "," ch "and" = " whois.nic.ch "," cl "=" whois.nic.cl "," cn "=" whois.cnnic.net.cn "," cz "=" whois.nic.cz "," de "=&G T "Whois.nic.de", "fr" = "whois.nic.fr", "Hu" and "whois.nic.hu", "ie" = "whois.domainregistry.ie", "I L "=" whois.isoc.org.il "," in "=" whois.ncst.ernet.in "," ir "=" whois.nic.ir "," MC "and" = "whois.ripe . Net "to" = "whois.tonic.to", "TV" and "Whois.tv", "Ru" and "whois.ripn.net", "org" and "Whois.pir"       . org "," aero "=" Whois.information.aero "," NL "and" whois.domain-registry.nl ");  if (!isset ($servers [$ext])) {die (' error:no matching NIC server found! ');       } $nic _server = $servers [$ext];       $output = "; Connect to whois serVer:if ($conn = Fsockopen ($nic _server)) {fputs ($conn, $domain. "    \ r \ n ");    while (!feof ($conn)) {$output. = fgets ($conn, 128);  } fclose ($conn); } else {die (' error:could does connect to '. $nic _server. '!'); } return $output;}

    Grammar:

    <?php$domain = "http://www.blog.koonk.com"; $result = Whois_query ($domain);p rint_r ($result);? >

    9. Verify your email address
    Sometimes, when filling out a form on a website, the user may enter the wrong email address, which verifies that the email address is valid.

    function Is_validemail ($email) {$check = 0;if (Filter_var ($email, Filter_validate_email)) {$check = 1;} return $check;}    

    Grammar:

    <?php$email = "blog@koonk.com"; $check = Is_validemail ($email); echo $check;/If the output is 1 and then e-mail is valid.? >

    10. Get the user's real IP

    function getrealipaddr () {   if (!emptyempty ($_server[' http_client_ip '))   {     $ip =$_server[' Http_client_ IP '];   }   ElseIf (!emptyempty ($_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; }

    Grammar:

    <?php$ip = Getrealipaddr (); Echo $ip;? >

    11. Convert URL: Change from string to hyperlink
    If you are developing a forum, a blog or a regular form submission, a lot of times users have to visit a website. With this function, the URL string can be automatically converted to a hyperlink.

    function Makeclickablelinks ($text) {  $text = Eregi_replace (' (((f|ht) {1}tp://) [-a-za-z0-9@:%_+.~#?&//=]+] ',  ' \1 ', $text);  $text = Eregi_replace (' ([: Space:] () [{}]) (www.[ -a-za-z0-9@:%_+.~#?&//=]+) ',  ' \1\2 ', $text);  $text = Eregi_replace (' ([_.0-9a-z-]+@ ([0-9a-z][0-9a-z-]+.)] +[a-z]{2,3}) ',  ' \1 ', $text);      return $text; }   

    Grammar:

    <?php$text = "This was my first post on http://blog.koonk.com"; $text = Makeclickablelinks ($text); Echo $text; >

    12. Block multiple IPs from accessing your site
    This code snippet allows you to prohibit certain IP addresses from accessing your website

    if (!file_exists (' Blocked_ips.txt ')) {$deny _ips = array (' 127.0.0.1 ', ' 192.168.1.1 ', ' 83.76.27.9 ', ' 192.168.1.163 ');} else {$deny _ips = file (' Blocked_ips.txt ');} Read User IP adress: $ip = isset ($_server[' remote_addr ')? Trim ($_server[' remote_addr '): ";    Search current IP in $deny _ips arrayif ((Array_search ($ip, $deny _ips))!== FALSE) {//address is Blocked:echo ' Your IP adress ('. $ip. ') was blocked! '; Exit;}

    13. Mandatory File Download
    If you need to download a specific file without opening a new window, the following code snippet can help you.

    function Force_download ($file) {  $dir   = ": /log/exports/";  if (Isset ($file)) && (File_exists ($dir. $file)) {    header ("Content-type:application/force-download");    Header (' Content-disposition:inline; Filename= '. $dir. $file. '"');    Header ("Content-transfer-encoding:binary");    Header ("Content-length:". FileSize ($dir. $file));    Header (' Content-type:application/octet-stream ');    Header (' content-disposition:attachment; Filename= '. $file. '"');    ReadFile ("$dir $file");  } else {    echo "No file selected";  }}

    Grammar:

     
      

    14. Creating JSON Data
    Use the following PHP fragment to create JSON data that makes it easy for you to create a WEB service for your mobile app

    $json _data = array (' ID ' =>1, ' name ' = ' Mohit '); Echo json_encode ($json _data);

    15. Compressing the zip file
    Zip files can be compressed instantly using the following PHP fragment

    function Create_zip ($files = Array (), $destination = ", $overwrite = False) {//if The zip file already exists and OVERWR   ITE is false, return False if (file_exists ($destination) &&! $overwrite) {return false;}   VARs $valid _files = Array ();   If files were passed in ...       if (Is_array ($files)) {//cycle through each file foreach ($files as $file) {//make sure the file exists       if (file_exists ($file)) {$valid _files[] = $file;      }}}//if we have good files ... if (count ($valid _files)) {//create the archive $zip = new ziparchive (); if ($zip->open ($destination, $overwrite?     Ziparchive::overwrite:ziparchive::create)!== true) {return false;     }//add the files foreach ($valid _files as $file) {$zip->addfile ($file, $file);              }//debug//echo ' The zip archive contains ', $zip->numfiles, ' files with a status of ', $zip->status;     Close the zip--done! $zip->close ();   Check to make sure the file exists return file_exists ($destination);   } else {return false;    } }

    Grammar:

    <?php$files=array (' file1.jpg ', ' file2.jpg ', ' file3.gif '); Create_zip ($files, ' Myzipfile.zip ', true);? >

    16. Extracting Files

    function unzip ($location, $newLocation) {    if (EXEC ("Unzip $location", $arr)) {      mkdir ($newLocation);      for ($i = 1; $i < count ($arr), $i + +) {        $file = Trim (Preg_replace ("~inflating: ~", "", $arr [$i]));        Copy ($location. ' /'. $file, $newLocation. ' /'. $file);        Unlink ($location. ' /'. $file);      }      return TRUE;    } else{      return FALSE;    }}

    Grammar:

    <?phpunzip (' Test.zip ', ' unziped/test '); File would is unzipped in Unziped/test folder?>

    17. Zoom Image

    function Resize_image ($filename, $tmpname, $xmax, $ymax) {   $ext = explode (".", $filename);   $ext = $ext [Count ($ext)-1];        if ($ext = = "JPG" | | $ext = = "jpeg")     $im = Imagecreatefromjpeg ($tmpname);   ElseIf ($ext = = "png")     $im = Imagecreatefrompng ($tmpname);   ElseIf ($ext = = "gif")     $im = Imagecreatefromgif ($tmpname);          $x = Imagesx ($im);   $y = Imagesy ($im);          if ($x <= $xmax && $y <= $ymax)     return $im;        if ($x >= $y) {     $newx = $xmax;     $newy = $newx * $y/$x;   }   else {     $newy = $ymax;     $NEWX = $x/$y * $newy;   }          $im 2 = Imagecreatetruecolor ($newx, $newy);   Imagecopyresized ($im 2, $im, 0, 0, 0, 0, Floor ($newx), Floor ($newy), $x, $y);   return $im 2; }

    18. Send mail using mail ()
    We've previously provided snippets of PHP code to send mail using Mandrill, but if you don't want to use a third-party service, you can use the following PHP snippet.

    function Send_mail ($to, $subject, $body) {$headers = "from:koonk\r\n"; $headers. = "reply-to:blog@koonk.com\r\n"; $ Headers. = "return-path:blog@koonk.com\r\n"; $headers. = "x-mailer:php5\n"; $headers. = ' mime-version:1.0 '. "\ n"; $headers. = ' content-type:text/html; Charset=iso-8859-1 '. "\ r \ n"; Mail ($to, $subject, $body, $headers);}   

    Grammar:

    <?php$to = "admin@koonk.com"; $subject = "This is a Test mail"; $body = "Hello world!"; Send_mail ($to, $subject, $body);? >

    19. Convert seconds to days, hours and minutes

    function Secstostr ($secs) {  if ($secs >=86400) {$days =floor ($secs/86400); $secs = $secs%86400; $r = $days. ' Day '; if ($days <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}  if ($secs >=3600) {$hours =floor ($secs/3600), $secs = $secs%3600; $r. = $hours. ' Hour '; if ($hours <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}  if ($secs >=60) {$minutes =floor ($secs/60), $secs = $secs%60; $r. = $minutes. ' Minute '; if ($minutes <>1) {$r. = ' s ';} if ($secs >0) {$r. = ', ';}}  $r. = $secs. ' Second '; if ($secs <>1) {$r. = ' s ';}  return $r;}

    Grammar:

    <?php$seconds = "56789"; $output = Secstostr ($seconds); Echo $output; >

    20. Database connection
    Connect to MySQL Database

    <?php$dbname = ' Koonk '; $HOST = ' localhost '; $DBUSER = ' root '; $DBPASS = ' Koonk '; $CONNECT = mysql_connect ($HOST, $DBUSER, $DBPASS); if (! $CONNECT) {  echo ' MySQL Error: '. mysql_error ();} $SELECT = mysql_select_db ($DBNAME), if (! $SELECT) {  echo ' mysql Error: '. mysql_error ();}? >

    21. Catalogue List
    Use the following PHP code snippet to list all files and folders in a directory

    function List_files ($dir) {  if (Is_dir ($dir))  {    if ($handle = Opendir ($dir))    {while      ($file = Readdir ($handle))!== false)      {        if ($file! = "." && $file! = ":" && $file! = "Thumbs.db"/*pesky win dows, images. */)        {          echo '. $file. '. ' \ n ";        }      }      Closedir ($handle);}}  

    Grammar:

    <?php  list_files ("images/");//this would list all files of images folder?>

    22. Detecting User Language
    Use the following PHP code snippet to detect the language used by the user's browser

    function Get_client_language ($availableLanguages, $default = ' en ') {  if (isset ($_server[' http_accept_language ')) {    $langs =explode (', ', $_server[' http_accept_language '));    foreach ($langs as $value) {      $choice =substr ($value, 0,2);      if (In_array ($choice, $availableLanguages)) {        return $choice;      }    }  }  return $default;}

    23. View the CSV file

    function Readcsv ($csvFile) {  $file _handle = fopen ($csvFile, ' R ');  while (!feof ($file _handle)) {    $line _of_text[] = fgetcsv ($file _handle, 1024x768);  }  Fclose ($file _handle);  return $line _of_text;}  

    Grammar:

    <?php$csvfile = "Test.csv"; $csv = Readcsv ($csvFile); $a = csv[0][0]; This'll get value of Column 1 & Row 1?>

    The above is the whole content of this article, I hope that everyone's study has helped.

    Articles you may be interested in:

      • 7 super-useful PHP code Snippets
      • 10 useful snippets of PHP code
      • Common string processing code snippet collation in PHP
      • Super-Functional 7 PHP snippet sharing
      • PHP Security Detection Code snippet (share)
      • 19 Super-useful PHP code Snippets
      • 9 Classic PHP Code snippets to share
      • 9 Useful PHP code snippets to share
      • 10 super-useful PHP code Snippets
      • 6 super-useful PHP code Snippets

    http://www.bkjia.com/PHPjc/1098697.html www.bkjia.com true http://www.bkjia.com/PHPjc/1098697.html techarticle must be a collection of 23 PHP practical code Snippets, when writing code, there is a magic tool is always good! Here is a collection of 40+ PHP code snippets that can help you develop PHP projects ...

  • 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.