19 Practical PHP code snippets _ PHP Tutorial

Source: Internet
Author: User
19 ultra-practical PHP code snippets. Every Programmer and developer likes to discuss their favorite code snippets, especially when PHP developers spend several hours coding webpages or creating applications, they know more about the code. every programmer and developer prefers to discuss their favorite code snippets, especially when PHP developers spend several hours coding webpages or creating applications, they are more aware of the importance of the code. To save coding time, Xiaobian collects some useful code snippets to help developers improve their work efficiency.

1) Whois query using PHP -- use PHP to obtain Whois request. use this code to obtain whois information in a specific domain name. Take the domain name as a parameter and display the relevant information of 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 </A> // $ 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.internic.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 "=>" wh Ois.ripe.net "," au "=>" 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 "=>" 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. domainregis Try. 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, 43 )) {fputs ($ conn, $ domain. "\ r \ n"); while (! Feof ($ conn) {$ output. = fgets ($ conn, 128);} fclose ($ conn);} else {die ('Error: cocould not connect '. $ nic_server. '! ');} Return $ output;} 2) Text messaging with PHP using the TextMagic API -- use TextMagic API to obtain the PHP Test information TextMagic introduces a powerful core API, you can easily send SMS messages to your mobile phone. This API is billed. 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 '2017-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 the memory usage code to help you Get the memory usage. The code is as follows: 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_usage (). "bytes \ n";/* prints Final: 885912 bytes */echo "Peak :". memory_get_peak_usage (). "bytes \ n";/* prin Ts Peak: 13687072 bytes */4) Display source code of any webpage -- view the source code of any web page. if you want to view the source code of the web page, you only need to change the URL of the second line, the source code is displayed on the webpage. The code is as follows: $ Line) {// loop thru each line and prepend line numbers echo "Line # {$ line_num }:". htmlspecialchars ($ line ). "\ n";} 5) Create data uri's -- Create a data uri by using this code, you can Create a data Uri, which is very useful for embedding images in HTML/CSS, it can help save HTTP requests. The code is as follows: function data_uri ($ file, $ mime) {$ contents = file_get_contents ($ file); $ base64 = base64_encode ($ contents); echo "data: $ mime; base64, $ base64 ";} 6) Detect location by IP -- retrieve the geographic location through IP address. this code helps you find a specific IP address. you only need to enter an IP address in the function parameter to check the location. The code is as follows: function detect_city ($ ip) {$ default = 'unknown '; if (! Is_string ($ ip) | strlen ($ ip) <1 | $ ip = '2017. 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, rows => 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 ('{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 the code script language used by the browser language detection 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) check if server is HTTPS -- Check whether the SERVER has the following HTTPS code: if ($ _ server ['https']! = "On") {echo "This is not HTTPS";} else {echo "This is HTTPS";} 9) Generate CSV file from a PHP array--generate the. CSV file code in the PHP Group: function generateCsv ($ data, $ delimiter = ',', $ enclosure = '"') {$ handle = fopen ('php: // temp ', 'R + '); foreach ($ data as $ line) {fputcsv ($ handle, $ line, $ delimiter, $ enclosure);} rewind ($ handle); while (! Feof ($ handle) {$ contents. = fread ($ handle, 8192);} fclose ($ handle); return $ contents;} 10. code for finding the distance between Longitudes and Latitudes: function getDistanceBetweenPointsNew ($ latitude1, $ longitude1, $ latitude2, $ longitude2) {$ theta = $ longitude1-$ longitude2; $ miles = (sin (deg 2rad ($ latitude1) * sin (deg 2rad ($ latitude2) + (cos (deg 2rad ($ latitude1 )) * cos (deg 2rad ($ latitude2) * cos (deg 2rad ($ 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', 'yzs ', 'kilometers ', 'meters');} $ point1 = array ('lat' => 40.770623, 'long' =>-73.964367 ); $ point2 = array ('lat' => 40.758224, 'long' =>-73.917404); $ distance = getDistanceBetweenPointsNe W ($ point1 ['lat'], $ point1 ['long'], $ point2 ['lat'], $ point2 ['long']); foreach ($ distance as $ unit => $ value) {echo $ unit. ':'. number_format ($ value, 4 ). '';} The example returns the following: Code: miles: 2.6025 feet: 13,741.4350 yards: 4,580.4783 kilometers: 4.1884 meters: 4,188.3894 11. the code for perfecting the cURL function is as follows: function xcurl ($ url, $ ref = null, $ post = array (), $ ua = "Mozilla/5.0 (X11; Linux x86_64; rv: 2.2a1pre) Geck O/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. enter the following code to clear the user: ] *?>. *? Script @ Si', // Strip out javascript '@ <[\/\!] *? [^ <>] *?> @ 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_escape_string ($ input);} return $ output ;}?> 13. the code for detecting geographic locations by IP address (city or country) is as follows: function detect_city ($ ip) {$ default = 'Hollywood, Ca'; if (! Is_string ($ ip) | strlen ($ ip) <1 | $ ip = '2017. 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, rows => 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 ('{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. the code for setting the password strength is 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> 100) {$ strength = 100;} 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. check the browser language. only available $ availableLanguages can be used as an array ('en', 'De', 'el'). The code is 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, $ availableLanguages )){ Return $ choice ;}}return $ default;} 16. the code for creating a data URL is as follows: function data_uri ($ file, $ mime) {$ contents = file_get_contents ($ file); $ base64 = base64_encode ($ contents); echo "data: $ mime; base64, $ base64 ";} 17. create a more user-friendly seo url input example: $ title = "This foo's bar is rockin 'Cool! "; Echo makeseoname ($ title); // RETURNS: // this-foos-bar-is-rockin-cool code: function make_seo_name ($ title) {return preg_replace ('/[^ a-z0-9 _-]/I', '', strtolower (str_replace ('', '-', trim ($ title ))));} 18. the code for the ultimate encryption function is as follows: // f (ucking) u (ncrackable) e (ncryption) function by BlackHatDBL (www.netforme.net) function fue ($ hash, $ times) {// Execute the encryption (s) as frequently times as the user wants for ($ I = $ times; $ I> 0; $ I --) {// Encode with base64... $ hash = base64_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 = 20) {$ 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;} public function getTweets () {$ this-> twitterArr = $ this-> getTimelineArray (); $ tweets = array (); foreach ($ this-> twitterArr-> status as $ status) {$ tweets [$ status-> created_at->__ toString ()] = $ status-> text->__ String () ;}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 -- used to create a file in a topic, for example, example. the php code is as follows: loadTimeline ("phpsnips")-> getTweets (); foreach ($ feed as $ time => $ message) {echo"

". $ Twitter-> formatTweet ($ message )."
At: ". $ time ."

";}

...

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.