search
HomeBackend DevelopmentPHP Tutorial非常实用的PHP代码片段推荐_PHP

当使用PHP进行开发的时候,如果你自己收 藏 了一些非常有用的方法或者代码片段,那么将会给你的开发工作带来极大的便利。今天我们将介绍10个超级好用的PHP代码片段,希望大家能够喜欢!

1.  使用textmagic API发送消息

可能有的时候,你需要发送一些短信给你的客户,那么你绝对应该看看textMagic。它提供了非常简单的API来实现这个功能。但是不是免费的。

// 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 )

2.  通过IP判断来源

这是一个非常实用的代码片段,可以帮助你通过IP来判断访客来源。下面的方法通过接收一个参数,然后返回IP所在地点。如果没有找到,则返回UNKNOWN。

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

    }

3.  显示任何网页的源代码

是不是想显示带有行号的任何网页的源代码?这里有个简单的代码片段,你只需要修改第二行的url即可。  

<?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";
}

4.  判断服务器是否是HTTPS连接

需要判断代码运行环境是否是HTTPS服务器?下面的代码可以帮助你实现,非常简单!

if ($_SERVER[&#39;HTTPS&#39;] != "on") {
	echo "This is not HTTPS";
}else{
	echo "This is HTTPS";
}

5.  在文本中显示Facebook 粉丝数

想看看你在facebook有多少粉丝么?下面代码可以帮助你实现。

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.  判断一张图片的主色调

下面这个代码非常实用,能帮助你判断一张图片中的主色调,你可以分析任何图片。

$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);

7. 了解你的内存使用情况

为了优化你的脚本,你需要了解服务器上的RAM使用情况。这个代码片段将帮助你了解内存使用,并且打印初始、最终以及峰值使用情况。

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
*/

8.  使用gzcompress()压缩数据

当使用很长的string时,可以通过gzcompress()方法,将strings压缩。解压缩使用gzuncompress()即可。代码如下。

$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.  使用PHP执行Whois查询

如果你需要得到指定域名的whois信息,为什么不使用PHP呢?下面的代码可以帮助大家。

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

10.  不显示PHP错误而发送电子邮件取代之

如果你不想在页面中显示PHP错误,也可以通过email来获取错误信息。下面的代码可以帮助你实现。

<?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="brush:php;toolbar:false">" . print_r($vars, 1) . "
"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // 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

英文原文:10 super useful PHP snippets you probably haven’t seen

Statement
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
如何使用正则表达式批量修改PHP代码以满足最新的代码规范?如何使用正则表达式批量修改PHP代码以满足最新的代码规范?Sep 05, 2023 pm 03:57 PM

如何使用正则表达式批量修改PHP代码以满足最新的代码规范?导言:随着时间推移和技术的发展,代码规范也在不断更新和改进。在开发过程中,我们经常需要对旧有的代码进行修改以符合最新的代码规范。然而,手动修改可以是一项繁琐且耗时的任务。在这种情况下,正则表达式可以成为一个有力的工具。利用正则表达式,我们可以批量修改代码并自动满足最新的代码规范。一、准备工作:在使用正

怎样在浏览器中编写PHP代码并保持代码不被执行?怎样在浏览器中编写PHP代码并保持代码不被执行?Mar 10, 2024 pm 02:27 PM

怎样在浏览器中编写PHP代码并保持代码不被执行?随着互联网的普及,越来越多的人开始接触网页开发,其中对于PHP的学习也越来越受到关注。PHP是一种在服务器端运行的脚本语言,通常用于编写动态网页。然而,在练习阶段,我们希望能够在浏览器中编写PHP代码并查看结果,但又不希望代码被执行。那么,如何实现在浏览器中编写PHP代码并保持不被执行呢?下面将详细介绍。首先,

PHP代码实现百度文心一言API接口的请求参数加密和解密处理PHP代码实现百度文心一言API接口的请求参数加密和解密处理Aug 16, 2023 pm 11:40 PM

PHP代码实现百度文心一言API接口的请求参数加密和解密处理一言(Hitokoto)是一个提供获取随机句子的服务,百度文心一言API是其中一个允许开发者调用的接口。为了确保数据的安全性,我们可以对请求参数进行加密处理,同时在接收到响应后进行解密操作。以下是PHP代码实现百度文心一言API接口的请求参数加密和解密处理的示例:&lt;?phpfunction

如何利用php代码测试功能提高代码的可维护性如何利用php代码测试功能提高代码的可维护性Aug 11, 2023 pm 12:43 PM

如何利用PHP代码测试功能提高代码的可维护性在软件开发过程中,代码的可维护性是一个非常重要的方面。一个可维护性高的代码意味着它易于理解、易于修改和易于维护。而测试是非常有效的一种提高代码可维护性的手段。本文将介绍如何利用PHP代码测试功能来达到这个目的,并提供相关的代码示例。单元测试单元测试是软件开发中常用的一种测试方法,用于验证代码中最小的可测试单元。在P

刨析php代码测试功能及其重要性刨析php代码测试功能及其重要性Aug 11, 2023 pm 03:12 PM

刨析php代码测试功能及其重要性前言:在软件开发过程中,代码测试是一个不可或缺的环节。通过对代码进行测试,可以有效地发现及解决潜在的bug和错误,提高代码的质量和稳定性。在php开发中,测试功能同样具有重要性。本文将深入探讨php代码测试的功能及其重要性,并结合实例进行说明。一、php代码测试的功能单元测试(UnitTesting)单元测试是最常见的测试方

调试 PHP 代码中的报错和意外行为调试 PHP 代码中的报错和意外行为Aug 12, 2023 pm 04:49 PM

标题:PHP代码调试:解析报错和意外行为导言:在开发PHP应用程序时,调试是一个重要的技能。当我们的代码出现报错或意外行为时,我们需要快速地定位问题并进行修复。本文将探讨一些常见的PHP错误和意外行为,并给出相应的代码示例和调试方法。一、语法错误语法错误是最常见的错误之一。在PHP中,语法错误会导致整个脚本无法正常执行。下面是一个示例代码:&lt;?php

PHP代码静态分析和漏洞检测技术PHP代码静态分析和漏洞检测技术Aug 07, 2023 pm 05:21 PM

PHP代码静态分析和漏洞检测技术引言:随着互联网的发展,PHP作为一种非常流行的服务器端脚本语言,被广泛应用于网站开发和动态网页生成。然而,由于PHP语法灵活而不规范的特性,导致在开发过程中容易引入安全漏洞。为了解决这个问题,PHP代码静态分析和漏洞检测技术应运而生。一、静态分析技术静态分析技术是指在代码运行之前通过解析源代码,使用静态规则来识别潜在的安全问

如何自动化检查PHP代码是否符合最新的代码规范?如何自动化检查PHP代码是否符合最新的代码规范?Sep 06, 2023 pm 12:33 PM

如何使用工具自动化检查PHP代码是否符合最新的代码规范?引言:在软件开发过程中,我们经常需要遵循一定的代码规范来保障代码的可读性、可维护性和可扩展性。但是,手动检查代码规范是一项繁琐且容易出错的任务。为了提高效率和减少错误,我们可以使用一些工具来自动化检查代码规范。在本文中,我将介绍如何使用一些流行的工具来自动化检查PHP代码是否符合最新的代码规范。一、PH

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!