23 PHP Practical code clips that must be collected _php tips

Source: Internet
Author: User
Tags curl explode sql injection trim urlencode web services ziparchive ssl certificate

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.
These PHP clips are also very helpful to PHP beginners, very easy to learn, let's start learning ~
1. Send SMS
When developing a Web or mobile application, you often encounter the need to send SMS to the user, or because of the logon reason, or to send information 。 The following PHP code implements the function of sending SMS.
to send SMS in any language, an SMS gateway is required. Most SMS provides an API for using MSG91 as the SMS gateway.

function Send_sms ($mobile, $msg) {$authKey = "xxxxxxxxxxx"; Date_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, ADD URL encoding here.
      
$message = UrlEncode ($msg);
Define route $route = "template"; Prepare your post parameters $postData = Array (' Authkey ' => $authKey, ' mobiles ' => $mobileNumber, ' message '
      
=> $message, ' sender ' => $senderId, ' route ' => $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 Verification curl_seTopt ($ch, curlopt_ssl_verifyhost, 0);
      
      
curl_setopt ($ch, Curlopt_ssl_verifypeer, 0);
Get Response $output = curl_exec ($ch);
      
Print error if any if (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. When you enter a mobile number, you need to specify the country code (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
Mandrill is a powerful SMTP provider. Developers tend to use a third-party SMTP provider to get better delivery.
In the following function, you need to put "mandrill.php" in the same folder, as a php file, so you can use TA to send mail.

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 (Array ("email" => $to _email));
$message->track_opens = true;
      
$response = $mandrill->messages->send ($message);

$apikey = ' xxxxxxxxxx '; Specify your API key here "you need to specify your API key (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 sites, use the following code 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 then the 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 = "<script>alert (1) </script>";
$text = Clean ($text);
echo $text;
? >

4. Detect User Location
Using the following function, you can detect the city in which the user is visiting your site

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 =&gt ;
      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 (' {<li>city: ([^<]*) </li>}i ', $content, $regs)) {$city = $regs [1]; } if (Preg_maTch (' {<li>state/province: ([^<]*) </li>}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 of 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 #< b>{$line _num}</b>: ". Htmlspecialchars ($line). "\ n";
}
}

Grammar:

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

6. Calculate a user who likes 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 picture

function Dominant_color ($image)
{
$i = imagecreatefromjpeg ($image);
For ($x =0 $x <imagesx ($i); $x + +) {for
  ($y =0; $y <imagesy ($i); $y + +) {
    $rgb = Imagecolorat ($i, $x, $y);
    $r  = ($rgb >>) & 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];  Your find lists//like to Wikipedia:////Http://de.wikipedia.org/wiki/Whois//$servers = Array ("Biz" => "whois.neulevel.biz", "com" => "whois.internic.net", "Us" => "whois.nic.us", " Coop "=>" 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" => "whois.iana.org", "AC" => "Whois.nic.ac", "AE" => "whois.uaenic.ae""," at "=>" whois.ripe.net "," au "=>" whois.aunic.net "," being "=>" whois.dns.be "," BG "=>" whois . Ripe.net "," BR "=>" whois.registro.br "," BZ "=>" Whois.belizenic.bz "," Ca "=>" whois.cira.ca "," CC "=>", "whois.nic.cc", "ch" => "whois.nic.ch", "CL" => "whois.nic.cl", "cn" => "whois.cnnic.net.cn" "," CZ "=>" whois.nic.cz "," de "=>" whois.nic.de "," fr "=>" whois.nic.fr "," Hu "=>" Whois.nic ".
    Hu "," ie "=>" whois.domainregistry.ie "," il "=>" whois.isoc.org.il "," in "=>" whois.ncst.ernet.in ", 
    "IR" => "whois.nic.ir", "MC" => "Whois.ripe.net", "to" => "whois.tonic.to", "TV" => "Whois.tv", "Ru" => "whois.ripn.net", "org" => "whois.pir.org", "Aero" => "Whois.information.aero", "NL" =&G T
     
  "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 not connect to '. $nic _server. '!');
return $output;
 }

Grammar:

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

9. Verify email address
Sometimes, when filling out a form on a Web site, 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, 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: From a string into a hyperlink
If you are developing a forum, a blog or a regular form submission, many times users will have to visit a website. Using 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@:%_+.~#?&//= ]+) ', 
 ' <a href= ' \1 ' >\1</a> ', $text); 
 $text = Eregi_replace ([[: Space:] () [{}]) (www.[ -a-za-z0-9@:%_+.~#?&//=]+) ', 
 ' \1<a href= ' http://\2 ' >\2</a> ', $text); 
 $text = Eregi_replace ([_.0-9a-z-]+@ (0-9a-z][0-9a-z-]+.) +[a-z]{2,3}) ', 
 ' <a href= ' mailto:\1 ' >\1</a> ', $text); 
     
return $text; 
}
   

Grammar:

<?php
$text = "This are my http://blog.koonk.com";
$text = Makeclickablelinks ($text);
echo $text;
? >

12. Block multiple IP access to your site
This code snippet allows you to prevent certain IP addresses from accessing your site.

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 array
if ((Array_search ($ip, $deny _ips))!== FALSE) {
 //address is blocked:< C15/>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 will 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:

<php
force_download ("image.jpg");
? >

14. Create JSON Data
Use the following PHP fragment to create JSON data that will make it easier for you to create WEB services for mobile applications

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

15. Compressed zip file
Use the following PHP fragment to instantly compress the zip file

function Create_zip ($files = Array (), $destination = ", $overwrite = False) {//if The zip file already exists and over 
  The write is false and 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 archive $zip = new Ziparch 
    Ive (); 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. Extract 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:

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

17. Zoom Picture

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 have previously provided a snippet of PHP code to send a message using Mandrill, but if you do not 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
Connecting to the 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 fragment 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 windows, images. */)
        {
          echo ' <a target= ' _blank ' href= '. $dir. $file. ' " > '. $file. ' </a> '. ' \ n ';
        }
      }
      Closedir ($handle);}}

Grammar:

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

22. Detect the User language
Use the following PHP code fragment 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 CSV File

function Readcsv ($csvFile) {
  $file _handle = fopen ($csvFile, ' R ');
  while (!feof ($file _handle)) {
    $line _of_text[] = fgetcsv ($file _handle, 1024);
  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 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.