When using PHP for development, if you own some very useful methods or snippets of code, it will be a great convenience for your development work. Today we will introduce 10 super useful PHP code snippets, I hope you can enjoy!
1. Sending messages using the Textmagic API
There may be times when you need to send some text messages to your customers, then you should definitely look at textmagic. It provides a very simple API to implement this functionality. But not for free.
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
2. Judging the source by IP
This is a very useful code snippet that can help you to determine the source of your visitors through IP. The following method receives a parameter and then returns the IP location point. If it is not found, it returns unknown.
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 any Web page
Do you want to display the source code for any page with line numbers? Here's a simple code snippet, you just need to change the URL of the second line
<?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. Determine if the server is an HTTPS connection
Need to determine if the code environment is an HTTPS server? The following code can help you to implement, very simple!
if ($_server[' https ']! = "on") {echo "This is not HTTPS"; } else{ echo "This is HTTPS"; }
5. Show Facebook fans in text
Want to see how many fans you have on Facebook? The following code can help you implement it.
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. Determine the main color of a picture
The following code is very useful to help you determine the main color of a picture, you can analyze any image.
$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. Understand your memory usage
To optimize your script, you need to know the RAM usage on the server. This code snippet will help you understand memory usage and print initial, final, and peak usage scenarios.
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 ()
When a long string is used, the strings can be compressed by means of the gzcompress () method. Unzip using gzuncompress (). The code is as follows.
$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. Using PHP to perform WHOIS queries
If you need to get whois information for a given domain name, why not use PHP? The following code can help you.
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" and "=" whois.internic.net "," Us "=" whois.nic.us "," Coop "and" Whois.nic.coop "," info "=" Whois.nic.info "," name "=" Whois.nic.name "," net "=" whois.internic.net "," gov "=" whois.ni " C.gov "," edu "=" WHOIS.INTERNIC.N "Et "," 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.ne " T "," be "=" whois.dns.be "," BG "and" Whois.ripe.net "," br "=" whois.registro.br " "," BZ "=" whois.belizenic.bz "," Ca "=" whois.cira.ca "," CC "and" 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" = "whois.nic.hu", "ie" = "whois.domainregistry.ie", "il" and "whois.isoc.org.il", "In" = "whois.ncst.ernet.in", "ir" = "whois.nic.ir", "MC" and "Whois.ripe.net", "to" and "="Whois.tonic.to "," TV "=" whois.tv "," Ru "and" whois.ripn.net "," org "=" whois.p Ir.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. Do not display PHP errors and send e-mail instead of
If you do not want to display PHP errors on the page, you can also get the error message via email. The following code can help you implement it.
<?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 I n 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, ' [email protected] ', $headers); Make sure this decide how to 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;? >