10 super-useful PHP code Snippets

Source: Internet
Author: User
Tags php error vars
1. Send SMS

Call the Textmagic API.

Include the Textmagic PHP lib  require (' textmagic-sms-api-php/textmagicapi.php ');   Set the username and password information  $username = ' myusername ';  $password = ' MyPassword ';   Create a new instance of TM  $router = new Textmagicapi (Array (      ' username ' = $username,      ' password ' = $password));   Send a text message to ' 999-123-4567 '  $result = $router->send (' Wake up! ', Array (9991234567), true);   Result:  result Is:array ([messages] = Array ([19896128] = 9991234567) [Sent_text] = Wake up! [Parts_count] = 1)

2. Find addresses based on IP

function Detect_city ($ip) {$default = ' UNKNOWN ';           if (!is_string ($IP) | | strlen ($IP) < 1 | | $ip = = ' 127.0.0.1 ' | | $ip = = ' localhost ') $ip = ' 8.8.8.8 '; $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, CU Rlopt_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)) {$st          ate = $regs [1]; if ($city! = "&& $state! =") {$location = $city. ', ' .            $state;          return $location;          }else{return $default; }       }

3. Display the source code of the Web page

<?php//Display source code  $lines = File (' http://google.com/');  foreach ($lines as $line _num + $line) {      //loop thru each line and prepend line numbers      echo ' line #<b>{ $line _num}</b>: ". Htmlspecialchars ($line). "<br>\n";  }

4. Check if the server is using HTTPS

if ($_server[' https ']! = "on") {echo "This is not      HTTPS";  } else{      echo "This is HTTPS";  }

5. Show the number of Facebook fans

function Fb_fan_count ($facebook _name) {      //Example:https://graph.facebook.com/digimantra      $data = Json_ Decode (file_get_contents ("https://graph.facebook.com/". $facebook _name));      echo $data->likes;  }

6. Detect the main color of the picture

$i = Imagecreatefromjpeg ("image.jpg");   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);

7. Get Memory usage information

echo "Initial:". Memory_get_usage (). "Bytes \ n";  /* Prints initial:361400 bytes *//Let's use up  some memory for  ($i = 0; $i < 100000; $i + +) {      $a Rray []= MD5 ($i);  }   Let's remove half of the array for  ($i = 0; $i < 100000; $i + +) {      unset ($array [$i]);  }   echo "Final:". Memory_get_usage (). "Bytes \ n";  /* Prints  final:885912 bytes  *  /echo "Peak:". Memory_get_peak_usage (). "Bytes \  n"; /* Prints  peak:13687072 bytes  */

8. Compressing data using gzcompress ()

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc ut elit id mi ultricies adipiscing. Nulla Facilisi. Praesent pulvinar, sapien vel feugiat vestibulum, nulla dui pretium orci, non ultricies elit lacus quis ante. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam pretium ullamcorper urna quis iaculis. Etiam ac massa sed turpis tempor luctus. Curabitur sed nibh eu elit mollis congue. Praesent ipsum diam, Consectetur vitae ornare A, aliquam a nunc. In ID magna pellentesque tellus posuere adipiscing. Sed non mi metus, at Lacinia Augue. Sed magna nisi, ornare in mollis in, mollis sed nunc.  Etiam at Justo in Leo Congue mollis. Nullam in Neque eget metus hendrerit scelerisque eu non enim. Ut malesuada lacus EU nulla bibendum ID euismod urna sodales.   ";   $compressed = gzcompress ($string); echo "Original size:". Strlen ($string). "  \ n "; /* Prints Original size:800 */echo "Compressed size:". Strlen ($compressed). "  \ n "; /* Prints COMPRessed size:418 *///Getting it back $original = gzuncompress ($compressed); 

9. Use PHP for whois checking

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", "u S "=" whois.nic.us "," coop "=" Whois.nic.coop "," info "=" Whois.nic.info "," name "= > "Whois.nic.name", "net" = "whois.internic.net", "gov" = "whois.nic.gov", "edu" =&G T "Whois.internic.net", "mil" = "rs.internic.net", "int" = "whois.iana.org", "ac" = "whois.nic.ac", "ae" = "whois.uaenic.ae", "at" and "W" Hois.ripe.net "," au "=" whois.aunic.net "," be "=" whois.dns.be "," BG "and" 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" =&G T "Whois.nic.fr", "hu" = "whois.nic.hu", "ie" = "whois.domainregistry.ie", "il" and "WH" Ois.isoc.org.il "," in "=" whois.ncst.ernet.in "," ir "=" whois.nic.ir "," MC "and" = "whoi          S.ripe.net "," to "and" whois.tonic.to "," TV "=" whois.tv "," Ru "and" whois.ripn.net ", "Org" = "Whois.pir.org "," aero "=" 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; }

10. Send php error via email

<?php//Our custom error handler function Nettuts_error_handler ($number, $message, $file, $line, $vars) {$emai L = "<p>an error ($number) occurred on line <strong> $line </strong> and in the &LT;STR       Ong>file: $file .</strong> <p> $message </p> "; $email. = "<pre>". Print_r ($vars, 1).       "</pre>"; $headers = ' content-type:text/html; Charset=iso-8859-1 '.       "\ r \ n";       Email the error to someone Error_log ($email, 1, ' you@youremail.com ', $headers); Make sure so decide how to respond to errors (on the user's side)//either echo an error message, or kill T He entire project.      Up-to-you ...//the code below ensures that we only "die" if the error is more than//just a NOTICE. if ($number!== e_notice) && ($number < 2048)) {Die ("there is an error.   Please try again later. ");} We should use our custom function to HAndle errors.   Set_error_handler (' Nettuts_error_handler '); Trigger an error ... (Var doesn ' t exist) echo $somevarthatdoesnotexist;
  • 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.