Super-useful PHP code snippet

Source: Internet
Author: User
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, the author collects some useful code snippets to help the developers improve work efficiency.

1) Whois query using php--using PHP for WHOIS requests

With this code, WHOIS information is available in a specific domain name. Takes the domain name as a parameter and displays information about all domain names.

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:////<a href= "Http://de.wikipedia.org/wiki/Whois"        >http://de.wikipedia.org/wiki/Whois</a>//$servers = Array ("Biz" = "whois.neulevel.biz", "com" = "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" and "="      "Whois.nic.gov", "edu" = "whois.internic.net", "Mil" and "rs.internic.net",  "int" = "whois.iana.org", "ac" = "whois.nic.ac", "ae" = "whois.uaenic.ae", "at" and "=" Whois.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" and "=" whois.c        Nnic.net.cn "," cz "=" whois.nic.cz "," de "=" whois.nic.de "," fr "and" 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 "and" Whois.ripe.net "," to "and" WH "        Ois.tonic.to "," TV "=" whois.tv "," Ru "and" whois.ripn.net "," org "and" whois.pir.org ", "Aero" = "whois.in"Formation.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;}

2) Text Messaging with PHP using the textmagic api--use the textmagic API to get PHP test information

Textmagic introduces a powerful core API that makes it easy to send SMS to your phone. The API is required for a fee.

The Textmagic PHP librequire (' 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 (    ' username ' = $username,    ' password ' = = $pass Word)); 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 utilization

This code helps you get memory utilization.

echo "Initial:". Memory_get_usage (). "Bytes \ n";/* printsinitial:361400 bytes*///Let's use up some memoryfor ($i = 0; $ I < 100000; $i + +) {    $array []= MD5 ($i);}/Let's remove half of the arrayfor ($i = 0; $i < 100000; $i + +) {    unset ($array [$i ]);} echo "Final:". Memory_get_usage (). "Bytes \ n";/* printsfinal:885912 bytes*/echo "Peak:". Memory_get_peak_usage (). "Byte s \ n ";/* printspeak: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, just change the URL of the second line, and the source code will be displayed on the 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 #{$line _num } : " . Htmlspecialchars ($line). "\ n";}

5) Create data URI ' s--.

By using this code, you can create data URIs, which are useful for embedding images in Html/css, and can help save HTTP requests.

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--to retrieve geolocation via IP

This code helps you to find a specific IP, just enter the IP on the function parameters, you can detect the location.

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_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: ([^&L t;] *)}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.

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--to detect if the servers are HTTPS

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

9) Generate csv file from a php array--generate. CSV Files in PHP array

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;}
  • 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.