Another 10 super useful PHP code Snippets _php Tips

Source: Internet
Author: User
Tags curl explode memory usage php error strlen trim vars

Good things to share together, last shared 10, this time to come again 10 Super useful PHP code snippets.

1. Send SMS

Invoke 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, Curlopt_returntransfer => 1, Curlopt_useragent => $curlopt _useragent, Curlopt_url => $url, curlopt_timeout => 1, Curlopt_refe RER => ' 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; 
 } 
 
 }

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 that the server is using HTTPS

if ($_server[' HTTPS ']!= ' on ') {echo ' 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"; 
/* Prints 
peak:13687072 bytes 
* * 

8. Use Gzcompress () to compress data

$string = "Lorem ipsum dolor sit amet, consectetur adipiscing. 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. 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, 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 to do 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];  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.intern " Ic.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.R"Ipe.net "," au "=>" whois.aunic.net "," Be "=>" whois.dns.be "," BG "=>" Whois.ripe.net "," BR "=>" WH "  ois.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" => "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;  }


10. Send php error via email

<?php//Our custom error handler function Nettuts_error_handler ($number, $message, $file, $line, $vars) {$email = "<p>an error ($number) occurred on line <strong> $line </strong> and in the <strong>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 you decide and respond to errors (on the user's side)//either echo an error message, or kill the 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;

is also very exciting, and before the collection bar

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.