46 very useful snippets of PHP code (i)

Source: Internet
Author: User
Tags urlencode ziparchive ssl certificate
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.

[Code]php Code:

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, ' Mobile  s ' = = $mobileNumber, ' message ' + $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.

[Code]php Code:

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.

[Code]php Code:

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 = "<script>alert (1) </script>";

$text = Clean ($text);

Echo $text;

?>

4. Detecting User Locations

Use the following function to detect in which city the user visited your website

[Code]php Code:

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 (' {<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 for the Web page

Use the following function to get the HTML code for any Web page

[Code]php Code:

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). "<br>\n";}}

Grammar:

<?php

$url = "http://blog.koonk.com";

$source = Display_sourcecode ($url);

Echo $source;

?>

6. Calculate the users who like your Facebook page

[Code]php Code:

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

[Code]php Code:

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);} </imagesx ($i); $x + +) >

8. Whois query

Use the following function to get the full details of any domain user

[Code]php Code:

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 = Array ("Biz" = "whois.neulevel.biz", "com" = "whois.internic.net", "us" and "=" whoi S.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" and "whois.iana.org", "ac" = "whois". Nic.ac "," ae "=" whois.uaenic.ae "," at "=" whois.ripe.net "," au "and" whois.aunic.net ", "Be" = "whois.dns.be", "bg" = "whois.ripe.net", "br" = "whois.registro.br", "BZ" =&G T "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" and "whois.nic.fr", "Hu" and "whois.nic.hu", "ie" = "whois.domain registry.ie "," il "=" whois.isoc.org.il "," in "and" whois.ncst.ernet.in "," ir "=" whois.nic . ir "," mc "=" whois.ripe.net "," to "and" whois.tonic.to "," TV "=" whois.tv "," Ru "=& Gt "Whois.ripn.net", "org" = "whois.pir.org", "aero" = "Whois.information.aero", "NL" and "Who Is.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);

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

[Code]php Code:

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

[Code]php Code:

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.

[Code]php Code:

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

[Code]php Code:

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.

[Code]php Code:

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

[Code]php Code:

function Create_zip ($files = Array (), $destination = ", $overwrite = False) {//if The zip file already exists and Ove      Rwrite 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 archiveContains ', $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);

?>

The above is 46 very useful PHP code fragment (a) of the content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.