PHP to send SMS messages and many other useful PHP code sharing

Source: Internet
Author: User
Tags ziparchive ssl certificate
In programming, there will always be some very common needs, perhaps the predecessors have made us a good wheel, but we did not find. This article shares some common functional code snippets.

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 is 6 characters long $senderId = "Ikoonk";//your message to send, and Add URL encoding here. $message = Urlen     Code ($MSG);//define route $route = "template";//prepare you post Parameters$postdata = Array (' authkey ' = = $authKey, ' Mobiles ' = $mobileNumber, ' message ' and ' $message ', ' sender ' and ' $senderId, ' route ' = ' $route ');//ap I 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_ve Rifyhost, 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 ("email" = = $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 = "<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

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

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 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 <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]; 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.A"C "," ae "=" whois.uaenic.ae "," at "=" whois.ripe.net "," au "=" whois.aunic.net "," Be "+" whois.dns.be "," bg "=" whois.ripe.net "," br "=" whois.registro.br "," BZ "and" WH "        Ois.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" =& Gt "Whois.nic.de", "fr" = "whois.nic.fr", "Hu" and "whois.nic.hu", "ie" = "whois.domainregistr        y.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" and "WH" Ois.ripn.net "," org "=" whois.pir.org "," Aero "and" Whois.information.aero "," nl "+" 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@:%_+.~#?&//=]+] ',   ' <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

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:

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

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);?>

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