Table of Contents
Recommend 10 very practical PHP code snippets
Home Backend Development PHP Tutorial Recommend 10 very practical PHP code snippets_PHP tutorial

Recommend 10 very practical PHP code snippets_PHP tutorial

Jul 13, 2016 am 10:22 AM
code fragment

Recommend 10 very practical PHP code snippets

When developing using PHP, if you collect some very useful methods or code snippets, it will bring great convenience to your development work. Today we will introduce 10 super easy-to-use PHP code snippets. I hope you will like them!


1. Use textmagic API to send messages
There may be times when you need to send some text messages to your customers, then you should definitely check out textMagic. It provides a very simple API to implement this functionality. But it's not 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:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 ) 
Copy after login



2. Determine the source by IP
This is a very practical code snippet that can help you determine the source of your visitors by IP. The following method receives a parameter and then returns the IP location. If not found, UNKNOWN is returned.
function detect_city($ip) {  
 
        $default = 'UNKNOWN';  
 
        if (!is_string($ip) || strlen($ip) < 1 || $ip == &#39;127.0.0.1&#39; || $ip == &#39;localhost&#39;)  
            $ip = &#39;8.8.8.8&#39;;  
 
        $curlopt_useragent = &#39;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)&#39;;  
 
        $url = &#39;http://ipinfodb.com/ip_locator.php?ip=&#39; . 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         => &#39;http://&#39; . $_SERVER[&#39;HTTP_HOST&#39;],  
        );  
 
        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(&#39;{<li>City : ([^<]*)</li>}i&#39;, $content, $regs) )  {  
            $city = $regs[1];  
        }  
        if ( preg_match(&#39;{<li>State/Province : ([^<]*)</li>}i&#39;, $content, $regs) )  {  
            $state = $regs[1];  
        }  
 
        if( $city!=&#39;&#39; && $state!=&#39;&#39; ){  
          $location = $city . &#39;, &#39; . $state;  
          return $location;  
        }else{  
          return $default;  
        }  
} 
Copy after login


3. Display the source code of any web page
Want to display the source code of any web page with line numbers? Here is a simple code snippet, you only need to modify the url in the second line
<?php // display source code    
$lines = file(&#39;http://google.com/&#39;);    
foreach ($lines as $line_num => $line) {    
    // loop thru each line and prepend line numbers    
    echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";    
}   
?>
Copy after login



4. Determine whether the server is an HTTPS connection
Need to determine whether the code running environment is an HTTPS server? The code below can help you achieve it, it's very simple!
if ($_SERVER[&#39;HTTPS&#39;] != "on") {    
    echo "This is not HTTPS";    
}else{    
    echo "This is HTTPS";    
}    
Copy after login



5. Display Facebook fan count in text
Want to see how many fans you have on facebook? The code below can help you achieve this.
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;    
}    
   
Copy after login




6. Determine the main color of a picture
The code below is very practical and can help you determine the main color in a picture. You can analyze any 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 >> 16) & 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);    
Copy after login




7. Understand your memory usage
In order to optimize your scripts, you need to understand the RAM usage on the server. This code snippet will help you understand memory usage and print initial, final and peak usage.
echo "Initial: ".memory_get_usage()." bytes \n";    
/* prints   
Initial: 361400 bytes   
*/    
    
// let&#39;s use up some memory    
for ($i = 0; $i < 100000; $i++) {    
    $array []= md5($i);    
}    
    
// let&#39;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   
*/    
Copy after login



8. Use gzcompress() to compress data
When using very long strings, you can compress the strings through the gzcompress() method. To decompress, use 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); 
Copy after login




9. Use PHP to perform Whois query
If you need to get the whois information of a specific domain name, why not use PHP? The code below can help everyone.
function whois_query($domain) {    
    
    // fix the domain name:    
    $domain = strtolower(trim($domain));    
    $domain = preg_replace(&#39;/^http:\/\//i&#39;, &#39;&#39;, $domain);    
    $domain = preg_replace(&#39;/^www\./i&#39;, &#39;&#39;, $domain);    
    $domain = explode(&#39;/&#39;, $domain);    
    $domain = trim($domain[0]);    
    
    // split the TLD from domain name    
    $_domain = explode(&#39;.&#39;, $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" => "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" => "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" => "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(&#39;Error: No matching nic server found!&#39;);    
    }    
    
    $nic_server = $servers[$ext];    
    
    $output = &#39;&#39;;    
    
    // 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(&#39;Error: Could not connect to &#39; . $nic_server . &#39;!&#39;); }    
    
    return $output;    
}  
Copy after login



10. Do not display PHP errors and send emails instead
If you don't want PHP errors to be displayed on the page, you can also get error information via email. The code below can help you achieve this.
<?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 class="code">" . print_r($vars, 1) . "
Copy after login
"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "rn"; // Email the error to someone... error_log($email, 1, 'you@youremail.com', $headers); // Make sure that you 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 was more than // just a NOTICE. if ( ($number !== E_NOTICE) && ($number < 2048) ) { die("There was 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; ?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/847867.htmlTechArticleRecommend 10 very practical PHP code snippets. When developing with PHP, if you have collected some very Useful methods or code snippets that will give your development work...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve win7 driver code 28 How to solve win7 driver code 28 Dec 30, 2023 pm 11:55 PM

Some users encountered errors when installing the device, prompting error code 28. In fact, this is mainly due to the driver. We only need to solve the problem of win7 driver code 28. Let’s take a look at what should be done. Do it. What to do with win7 driver code 28: First, we need to click on the start menu in the lower left corner of the screen. Then, find and click the "Control Panel" option in the pop-up menu. This option is usually located at or near the bottom of the menu. After clicking, the system will automatically open the control panel interface. In the control panel, we can perform various system settings and management operations. This is the first step in the nostalgia cleaning level, I hope it helps. Then we need to proceed and enter the system and

What to do if the blue screen code 0x0000001 occurs What to do if the blue screen code 0x0000001 occurs Feb 23, 2024 am 08:09 AM

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

Solve the 'error: expected initializer before 'datatype'' problem in C++ code Solve the 'error: expected initializer before 'datatype'' problem in C++ code Aug 25, 2023 pm 01:24 PM

Solve the "error:expectedinitializerbefore'datatype'" problem in C++ code. In C++ programming, sometimes we encounter some compilation errors when writing code. One of the common errors is "error:expectedinitializerbefore'datatype'". This error usually occurs in a variable declaration or function definition and may cause the program to fail to compile correctly or

The computer frequently blue screens and the code is different every time The computer frequently blue screens and the code is different every time Jan 06, 2024 pm 10:53 PM

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Resolve code 0xc000007b error Resolve code 0xc000007b error Feb 18, 2024 pm 07:34 PM

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

Detailed explanation of the causes and solutions of 0x0000007f blue screen code Detailed explanation of the causes and solutions of 0x0000007f blue screen code Dec 25, 2023 pm 02:19 PM

Blue screen is a problem we often encounter when using the system. Depending on the error code, there will be many different reasons and solutions. For example, when we encounter the problem of stop: 0x0000007f, it may be a hardware or software error. Let’s follow the editor to find out the solution. 0x000000c5 blue screen code reason: Answer: The memory, CPU, and graphics card are suddenly overclocked, or the software is running incorrectly. Solution 1: 1. Keep pressing F8 to enter when booting, select safe mode, and press Enter to enter. 2. After entering safe mode, press win+r to open the run window, enter cmd, and press Enter. 3. In the command prompt window, enter "chkdsk /f /r", press Enter, and then press the y key. 4.

What does the blue screen code 0x000000d1 represent? What does the blue screen code 0x000000d1 represent? Feb 18, 2024 pm 01:35 PM

What does the 0x000000d1 blue screen code mean? In recent years, with the popularization of computers and the rapid development of the Internet, the stability and security issues of the operating system have become increasingly prominent. A common problem is blue screen errors, code 0x000000d1 is one of them. A blue screen error, or "Blue Screen of Death," is a condition that occurs when a computer experiences a severe system failure. When the system cannot recover from the error, the Windows operating system displays a blue screen with the error code on the screen. These error codes

GE universal remote codes program on any device GE universal remote codes program on any device Mar 02, 2024 pm 01:58 PM

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

See all articles