Every programmer and developer likes to discuss their favorite snippets of code, especially when PHP developers spend hours coding or creating apps for a Web page, and they know the importance of the code. In order to save the coding time, small series collected some more useful code snippets, to help developers improve productivity
1) Whois query using php--uses PHP to obtain WHOIS requests to use this code to obtain WHOIS information in a specific domain name. Takes the domain name as a parameter and displays information about all domain names. The code is as follows: 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" = "whois.nic.us", "Coop" and "whois.nic.co" Op "," info "=" Whois.nic.info "," name "=" Whois.nic.name "," net "=" whois.internic.net "," gov "=" whois.ni " C.gov "," edu "=" whois.internic.net "," mil "=" rs.internic.net "," int "=" whois.iana.org "," ac "=" WHOIS.N " Ic.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" = "whois.belizenic.bz", "Ca" = "whois.cira.ca", "cc" = "whois.nic.cc", "ch" = "W" hois.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 "and" WHOIS.ISOC.O " Rg.il "," in "=" whois.ncst.ernet.in "," ir "=" whois.nic.ir "," mc "=" whois.ripe.net "," to "and" Whois.tonic ". To "," TV "=" whois.tv "," Ru "and" whois.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, $);} fclose ($conn); } else {die (' error:could does connect to '. $nic _server. '!'); } return $output; } 2) Text Messaging with PHP using the textmagic api--use the Textmagic API to get PHP test information textmagic introduce a powerful core API that makes it easy to send SMS to your phone. The API is required for a fee. The code is as follows: 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) 3) Get info about your memory usage--get RAM usage this piece of code helps you get memory usage. The code looks like this: echo "Initial:". Memory_get_usage (). "Bytes \ n"; /* Prints initial:361400 bytes *//Let's use up some memory for($i = 0; $i < 100000; $i + +) {$array []= MD5 ($i);} Let's remove half of the array for ($i = 0; $i < 100000; $i + +) {unset ($array [$i]);} echo "Final:". Memory_get_usag E (). "Bytes \ n"; /* Prints final:885912 bytes */echo "Peak:". Memory_get_peak_usage (). "Bytes \ n"; /* Prints peak:13687072 bytes */4) display source code of any webpage--view any page source if you want to view the source code of the Web page, simply change the URL of the second line and the source code will appear on the page. The code is as follows: $line) {//loop thru prepend line numbers echo ' line #{$line _num}: '. Htmlspecialchars ($line). "\ n"; } 5) Create data URI ' s--creates a URI by using this code, you can create a data URI that is useful for embedding a picture in Html/css and can help save HTTP requests. The code is as follows: function Data_uri ($file, $mime) {$contents =file_get_contents ($file); $base 64=base64_encode ($contents); echo " Data: $mime; base64, $base 64 "; } 6) Detect location by ip--This code helps you to find a specific IP, just enter the IP on the function parameters to detect the position. The code is as follows: 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_userage NT = $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 (' {City: ([^<]*)}i ', $content, $regs)) {$city = $regs [1];} if (Preg_match (' {state/province: ([^ <]*) (}i ', $content, $regs)) {$state = $regs [1];} if ($city! = "&& $state! =") {$location = $city. ‘, ‘ . $state; return $location; }else{return $default;}} 7) Detect Browser language--View Browser language detects the code scripting language used by the browser. The code is as follows: function Get_client_language ($availableLanguages, $default = ' en ') {if (Isset ($_server[' http_accept_language ')) {$langs =explode (', ', $_server[' http_accept_language ')), foreach ($langs as $value) {$choice =substr ($value, 0,2); if ( In_array ($choice, $availableLanguages)) {return $choice;}} } return $default; } 8) The check if server is https--detects if the server is HTTPS code as follows: if ($_server[' https ']! = "on") {echo "This is not HTTPS";} else{echo "This is HTTPS";} 9) Generate csv file from a PHP array--generates a. CSV in the PHP array code as follows: function Generatecsv ($data, $delimiter = ', ', $enclosure = ' ") {$handle = fopen (' php://temp ', ' r+ '); foreach ($data as $line) {fputcsv ($handle, $line, $delimiter, $enclosure);} Rewi nd ($handle); while (!feof ($handle)) {$contents. = Fread ($handle, 8192);} fclose ($handle); return $contents; } 10. Find the distance code between longitudes and latitudes as follows: function getdistancebetweenpointsnew ($latitude 1, $longitude 1, $latitude 2, $ Longitude2) {$theta = $longitude 1-$longitude 2; $miles = (Sin (Deg2rad ($latitude 1)) * Sin (Deg2rad ($latitude 2)) + (cos (de G2rad ($latitude 1)) * cos (Deg2rad ($latitude 2)) * cos (Deg2rad ($theta))); $miles = ACOs ($miles); $miles = Rad2deg ($miles); $miles = $miles * 60 * 1.1515; $feet = $miles * 5280; $yards = $feet/3; $kilometers = $miles * 1.609344; $meters = $kilometers * 1000; Return compact (' Miles ', ' feet ', ' yards ', ' kilometers ', ' meters '); } $point 1 = array (' lat ' = = 40.770623, ' long ' =-73.964367); $point 2 = Array (' Lat ' => 40.758224, ' long ' =-73.917404); $distance = getdistancebetweenpointsnew ($point 1[' lat '), $point 1[' long '], $point 2[' lat '), $point 2[' long ']); foreach ($distance as $unit = + $value) {echo $unit. ': '. Number_format ($value, 4). ' '; } The example returns the following: The code is as follows: miles:2.6025 feet:13,741.4350 yards:4,580.4783 kilometers:4.1884 meters:4,1 88.3894 11. Complete the Curl function code as follows: function Xcurl ($url, $ref =null, $post =array (), $ua = "mozilla/5.0 (X11; Linux x86_64; Rv:2.2a1pre) gecko/20110324 firefox/4.2a1pre ", $print =false) {$ch = Curl_init (); curl_setopt ($ch, Curlopt_autoreferer, true); if (!empty ($ref)) {curl_setopt ($ch, Curlopt_referer, $ref);} curl_setopt ($ch, Curlopt_url, $url); curl_setopt ($ch, Curlopt_header, 0); curl_setopt ($ch, curlopt_followlocation, 1); curl_setopt ($ch, Curlopt_returntransfer, 1); if (!empty ($ua)) {curl_setopt ($ch, curlopt_useragent, $ua);} if (count ($post) > 0) {curl_setopt ($ch, Curlopt_post, 1); curl_setopt ($ch, Curlopt_postfields, $post); } $output = Curl_EXEC ($ch); Curl_close ($ch); if ($print) {print ($output);} else {return $output;}} 12. Clean up the user input code as follows: ]*?> @si ',//Strip out HTML tags ' @ ]*?>.*?@siU ',//Strip style tags properly ' @ @ '//Strip multi-line comments); $output = Preg_replace ($search, ", $input); return $output; }?> $val) {$output [$var] = sanitize ($val);}} else {if (GET_MAGIC_QUOTES_GPC ()) {$input = Stripslashes ($input);} $input = CleanInput ($input); $output = Mysql_real_es Cape_string ($input); } return $output;}? >13. Detection of geolocation codes by IP (city, Country): function detect_city ($ip) {$default = ' Hollywood, CA '; if (!is_string ($IP) | | strlen ($IP) & Lt 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_userage NT = $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 (' {City: ([^<]*)}i ', $content, $regs)) {$city = $regs [1];} if (Preg_match (' {state/province: ([^ <]*)}i ', $content, $regs)) {$state = $regs [1];} if ($city! = "&& $state! =") {$location = $city. ', ' . $state; return $location; }else{return $default;}} 14. Set the password strength code as follows: function Password_strength ($string) {$h = 0; $size = strlen ($string); foreach (Count_chars ($string, 1) as $v {$p = $v/$size; $h-= $p * LOG ($p)/log (2);} $strength = ($h/4) * 100; if ($strength >) {$strength = +;} return $strength; } var_dump (Password_strength ("Correct Horse Battery Staple")); echo "
"; Var_dump (Password_strength ("Super Monkey Ball")); echo "
"; Var_dump (Password_strength ("tr0ub4dor&3")); echo "
"; Var_dump (Password_strength ("abc123")); echo "
"; Var_dump (Password_strength ("Sweet")); 15. Detect the browser language, only provide the available $availablelanguages as an array (' en ', ' de ', ' es ') code as follows: function Get_client_language ($availableLanguages, $ default= ' en ') {if (Isset ($_server[' http_accept_language ')) {$langs =explode (', ', $_server[' http_accept_language ')) ; Start going through each one foreach ($langs as $value) {$choice =substr ($value, 0,2), if (In_array ($choice, $availableLan guages) {return $choice;}} } return $default; 16. Create the data URL code as follows: function Data_uri ($file, $mime) {$contents =file_get_contents ($file); $base 64=base64_encode ($ Contents); echo "Data: $mime; base64, $base 64"; 17. Create a more friendly page title SEO URL Input Example: $title = "This foo's Bar is Rockin ' cool!"; echo Makeseoname ($title); RETURNS: The//this-foos-bar-is-rockin-cool code is as follows: function Make_seo_name ($title) {return preg_replace ('/[^a-z0-9_-]/i ') , ', Strtolower (Str_replace (', '-', trim ($title))); }18. The ultimate encryption function code is as follows:/f (ucking) U (ncrackable) e (ncryption) function by Blackhatdbl (www.netforme.net) function Fue ($hash, $ Times) {//EXecute the encryption (s) as many times as the user wants for ($i = $times; $i >0; $i-) {//Encode with base64 ... $hash =base 64_encode ($hash); and MD5. $hash =md5 ($hash); SHA1. $hash =SHA1 ($hash); Sha256 ... (one more) $hash =hash ("sha256", $hash); sha512 $hash =hash ("sha512", $hash); }//Finaly, when done, return the value return $hash; } 19a. Tweeter Feed runner--Use any Twitter name to load user resources on any page. The code is as follows: Public function Loadtimeline ($user, $max =) {$this->twiturl. = ' statuses/user_timeline.xml?screen_name= '. $ User. ' &count= '. $max; $ch = Curl_init (); curl_setopt ($ch, Curlopt_url, $this->twiturl); curl_setopt ($ch, Curlopt_returntransfer, true); $this->xml = curl_exec ($ch); return $this; The Public Function gettweets () {$this->twitterarr = $this->gettimelinearray (); $tweets = Array (); foreach ($this- >twitterarr->status as $status) {$tweets [$status->created_at->__tostring ()] = $status->text->__ ToString (); } return $tweets; } Public Function GettimelineaRray () {return simplexml_load_string ($this->xml), Public function Formattweet ($tweet) {$tweet = Preg_replace ("/( HTTP (. +?)) (|$)/"," $1$3 ", $tweet); $tweet = Preg_replace ("/# (. +?) (\h|\w|$)/"," #$1$2 ", $tweet); $tweet = Preg_replace ("/@ (. +?) (\h|\w|$)/"," @$1$2 ", $tweet); return $tweet; } 19b. Tweeter Feed runner--is used to create files in the theme, such as: Example.php code as follows: Loadtimeline ("Phpsnips")->gettweets (); foreach ($feed as $time = + $message) {echo ". $twitter->formattweet ($message)."
At: ". $time.";}
http://www.bkjia.com/PHPjc/741819.html www.bkjia.com true http://www.bkjia.com/PHPjc/741819.html techarticle every programmer and developer likes to discuss their favorite snippets of code, especially when PHP developers spend hours coding or creating apps for their web pages, and they know more about the weight of the code ...