0

0

十个超级有用的PHP代码片段

php中文网

php中文网

发布时间:2016-06-21 08:51:07

|

1171人浏览过

|

来源于php中文网

原创

 

1. 发送短信

调用 TextMagic API。


  1. 		// Include the TextMagic PHP lib  
  2. require('textmagic-sms-api-php/TextMagicAPI.php');  
  3.  
  4. // Set the username and password information  
  5. $username = 'myusername';  
  6. $password = 'mypassword';  
  7.  
  8. // Create a new instance of TM  
  9. $router = new TextMagicAPI(array(  
  10.     'username' => $username,  
  11.     'password' => $password 
  12. ));  
  13.  
  14. // Send a text message to '999-123-4567'  
  15. $result = $router->send('Wake up!', array(9991234567), true);  
  16.  
  17. // result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 ) 

2. 根据IP查找地址


  1. 		function detect_city($ip) {  
  2.  
  3.         $default = 'UNKNOWN';  
  4.  
  5.         if (!is_string($ip)  strlen($ip) 
  6.             $ip = '8.8.8.8';  
  7.  
  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)';  
  9.  
  10.         $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);  
  11.         $ch = curl_init();  
  12.  
  13.         $curl_opt = array(  
  14.             CURLOPT_FOLLOWLOCATION  => 1,  
  15.             CURLOPT_HEADER      => 0,  
  16.             CURLOPT_RETURNTRANSFER  => 1,  
  17.             CURLOPT_USERAGENT   => $curlopt_useragent,  
  18.             CURLOPT_URL       => $url,  
  19.             CURLOPT_TIMEOUT         => 1,  
  20.             CURLOPT_REFERER         => 'http://' . $_SERVER['HTTP_HOST'],  
  21.         );  
  22.  
  23.         curl_setopt_array($ch, $curl_opt);  
  24.  
  25.         $content = curl_exec($ch);  
  26.  
  27.         if (!is_null($curl_info)) {  
  28.             $curl_info = curl_getinfo($ch);  
  29.         }  
  30.  
  31.         curl_close($ch);  
  32.  
  33.         if ( preg_match('{
  34. City : ([^}i', $content, $regs) )  {  
  35.             $city = $regs[1];  
  36.         }  
  37.         if ( preg_match('{
  38. State/Province : ([^}i', $content, $regs) )  {  
  39.             $state = $regs[1];  
  40.         }  
  41.  
  42.         if( $city!='' && $state!='' ){  
  43.           $location = $city . ', ' . $state;  
  44.           return $location;  
  45.         }else{  
  46.           return $default;  
  47.         }  
  48.  
  49.     } 

3. 显示网页的源代码


  1. 		
    	
  2. $lines = file('http://google.com/');  
  3. foreach ($lines as $line_num => $line) {  
  4.     // loop thru each line and prepend line numbers  
  5.     echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    \n";  

4. 检查服务器是否使用HTTPS


  1. 		if ($_SERVER['HTTPS'] != "on") {  
  2.     echo "This is not HTTPS";  
  3. }else{  
  4.     echo "This is HTTPS";  

5. 显示Facebook粉丝数量


  1. 		function fb_fan_count($facebook_name){  
  2.     // Example: https://graph.facebook.com/digimantra  
  3.     $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));  
  4.     echo $data->likes;  

6. 检测图片的主要颜色


  1. 		$i = imagecreatefromjpeg("image.jpg");  
  2.  
  3. for ($x=0;$x
  4.     for ($y=0;$y
  5.         $rgb = imagecolorat($i,$x,$y);  
  6.         $r   = ($rgb >> 16) & 0xFF;  
  7.         $g   = ($rgb >>  & 0xFF;  
  8.         $b   = $rgb & 0xFF;  
  9.  
  10.         $rTotal += $r;  
  11.         $gTotal += $g;  
  12.         $bTotal += $b;  
  13.         $total++;  
  14.     }  
  15. }  
  16.  
  17. $rAverage = round($rTotal/$total);  
  18. $gAverage = round($gTotal/$total);  
  19. $bAverage = round($bTotal/$total); 

7. 获取内存使用信息


  1. 		echo "Initial: ".memory_get_usage()." bytes \n";  
  2. /* prints
  3. Initial: 361400 bytes  
  4. */ 
  5.  
  6. // let's use up some memory  
  7. for ($i = 0; $i 
  8.     $array []= md5($i);  
  9. }  
  10.  
  11. // let's remove half of the array  
  12. for ($i = 0; $i 
  13.     unset($array[$i]);  
  14. }  
  15.  
  16. echo "Final: ".memory_get_usage()." bytes \n";  
  17. /* prints
  18. Final: 885912 bytes  
  19. */ 
  20.  
  21. echo "Peak: ".memory_get_peak_usage()." bytes \n";  
  22. /* prints
  23. Peak: 13687072 bytes  
  24. */ 

8. 使用 gzcompress() 压缩数据


  1. 		$string =  
  2. "Lorem ipsum dolor sit amet, consectetur  
  3. adipiscing elit. Nunc ut elit id mi ultricies  
  4. adipiscing. Nulla facilisi. Praesent pulvinar,  
  5. sapien vel feugiat vestibulum, nulla dui pretium orci,  
  6. non ultricies elit lacus quis ante. Lorem ipsum dolor  
  7. sit amet, consectetur adipiscing elit. Aliquam  
  8. pretium ullamcorper urna quis iaculis. Etiam ac massa  
  9. sed turpis tempor luctus. Curabitur sed nibh eu elit  
  10. mollis congue. Praesent ipsum diam, consectetur vitae  
  11. ornare a, aliquam a nunc. In id magna pellentesque  
  12. tellus posuere adipiscing. Sed non mi metus, at lacinia  
  13. augue. Sed magna nisi, ornare in mollis in, mollis  
  14. sed nunc. Etiam at justo in leo congue mollis.  
  15. Nullam in neque eget metus hendrerit scelerisque  
  16. eu non enim. Ut malesuada lacus eu nulla bibendum  
  17. id euismod urna sodales. ";  
  18.  
  19. $compressed = gzcompress($string);  
  20.  
  21. echo "Original size: ". strlen($string)."\n";  
  22. /* prints  
  23. Original size: 800  
  24. */  
  25.  
  26. echo "Compressed size: ". strlen($compressed)."\n";  
  27. /* prints  
  28. Compressed size: 418  
  29. */  
  30.  
  31. // getting it back  
  32. $original = gzuncompress($compressed); 

9. 使用PHP做Whois检查


  1. 		function whois_query($domain) {  
  2.  
  3.     // fix the domain name:  
  4.     $domain = strtolower(trim($domain));  
  5.     $domain = preg_replace('/^http:\/\//i', '', $domain);  
  6.     $domain = preg_replace('/^www\./i', '', $domain);  
  7.     $domain = explode('/', $domain);  
  8.     $domain = trim($domain[0]);  
  9.  
  10.     // split the TLD from domain name  
  11.     $_domain = explode('.', $domain);  
  12.     $lst = count($_domain)-1;  
  13.     $ext = $_domain[$lst];  
  14.  
  15.     // You find resources and lists  
  16.     // like these on wikipedia:  
  17.     //  
  18.     // http://de.wikipedia.org/wiki/Whois  
  19.     //  
  20.     $servers = array(  
  21.         "biz" => "whois.neulevel.biz",  
  22.         "com" => "whois.internic.net",  
  23.         "us" => "whois.nic.us",  
  24.         "coop" => "whois.nic.coop",  
  25.         "info" => "whois.nic.info",  
  26.         "name" => "whois.nic.name",  
  27.         "net" => "whois.internic.net",  
  28.         "gov" => "whois.nic.gov",  
  29.         "edu" => "whois.internic.net",  
  30.         "mil" => "rs.internic.net",  
  31.         "int" => "whois.iana.org",  
  32.         "ac" => "whois.nic.ac",  
  33.         "ae" => "whois.uaenic.ae",  
  34.         "at" => "whois.ripe.net",  
  35.         "au" => "whois.aunic.net",  
  36.         "be" => "whois.dns.be",  
  37.         "bg" => "whois.ripe.net",  
  38.         "br" => "whois.registro.br",  
  39.         "bz" => "whois.belizenic.bz",  
  40.         "ca" => "whois.cira.ca",  
  41.         "cc" => "whois.nic.cc",  
  42.         "ch" => "whois.nic.ch",  
  43.         "cl" => "whois.nic.cl",  
  44.         "cn" => "whois.cnnic.net.cn",  
  45.         "cz" => "whois.nic.cz",  
  46.         "de" => "whois.nic.de",  
  47.         "fr" => "whois.nic.fr",  
  48.         "hu" => "whois.nic.hu",  
  49.         "ie" => "whois.domainregistry.ie",  
  50.         "il" => "whois.isoc.org.il",  
  51.         "in" => "whois.ncst.ernet.in",  
  52.         "ir" => "whois.nic.ir",  
  53.         "mc" => "whois.ripe.net",  
  54.         "to" => "whois.tonic.to",  
  55.         "tv" => "whois.tv",  
  56.         "ru" => "whois.ripn.net",  
  57.         "org" => "whois.pir.org",  
  58.         "aero" => "whois.information.aero",  
  59.         "nl" => "whois.domain-registry.nl"  
  60.     );  
  61.  
  62.     if (!isset($servers[$ext])){  
  63.         die('Error: No matching nic server found!');  
  64.     }  
  65.  
  66.     $nic_server = $servers[$ext];  
  67.  
  68.     $output = '';  
  69.  
  70.     // connect to whois server:  
  71.     if ($conn = fsockopen ($nic_server, 43)) {  
  72.         fputs($conn, $domain."\r\n");  
  73.         while(!feof($conn)) {  
  74.             $output .= fgets($conn,128);  
  75.         }  
  76.         fclose($conn);  
  77.     }  
  78.     else { die('Error: Could not connect to ' . $nic_server . '!'); }  
  79.  
  80.     return $output;  

10. 通过Email发送PHP错误


  1. 		
    	
  2.  
  3. // Our custom error handler  
  4. function nettuts_error_handler($number, $message, $file, $line, $vars){  
  5.     $email = "  
  6.         

    An error ($number) occurred on line  

  7.         $line and in the file: $file.  
  8.         

     $message 

    ShoopD 网上商店系统
    ShoopD 网上商店系统

    用 php + mysql 驱动的在线商城系统,我们的目标为中国的中小企业及个人提供最简洁,最安全,最高效的在线商城解决方案,使用了自建的会员积分折扣功能,不同的会员组有不同的折扣,让您的商店吸引更多的后续客户。 系统自动加分处理功能,自动处理会员等级,免去人工处理的工作量,让您的商店运作起来更方便省事 采用了自建的直接模板技术,免去了模板解析时间,提高了代码利用效率 独立开发的购物车系统,使用最

    下载
    ";  
  9.  
  10.     $email .= "
    " . print_r($vars, 1) . "
    ";  
  11.  
  12.     $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";  
  13.  
  14.     // Email the error to someone...  
  15.     error_log($email, 1, 'you@youremail.com', $headers);  
  16.  
  17.     // Make sure that you decide how to respond to errors (on the user's side)  
  18.     // Either echo an error message, or kill the entire project. Up to you...  
  19.     // The code below ensures that we only "die" if the error was more than  
  20.     // just a NOTICE.  
  21.     if ( ($number !== E_NOTICE) && ($number 
  22.         die("There was an error. Please try again later.");  
  23.     }  
  24. }  
  25.  
  26. // We should use our custom function to handle errors.  
  27. set_error_handler('nettuts_error_handler');  
  28.  
  29. // Trigger an error... (var doesn't exist)  
  30. echo $somevarthatdoesnotexist; 



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
包子漫画网页版入口与全集阅读指南_正版免费漫画快速访问方法
包子漫画网页版入口与全集阅读指南_正版免费漫画快速访问方法

本专题汇总了包子漫画官网和网页版入口,提供最新章节抢先看方法、正版免费阅读指南,以及稳定访问方式,帮助用户快速直达包子漫画页面,无广告畅享全集漫画内容。

24

2026.02.10

MC.JS网页版快速畅玩指南_MC.JS官网在线入口及免安装体验方法
MC.JS网页版快速畅玩指南_MC.JS官网在线入口及免安装体验方法

本专题汇总了MC.JS官网入口和网页版快速畅玩方法,提供免安装访问、不同版本(1.8.8、1.12.8)在线体验指南,以及正版网页端操作说明,帮助玩家轻松进入MC.JS世界,实现即时畅玩与高效体验。

16

2026.02.10

谷歌邮箱网页版登录与注册全指南_Gmail账号快速访问与安全操作教程
谷歌邮箱网页版登录与注册全指南_Gmail账号快速访问与安全操作教程

本专题汇总了谷歌邮箱网页版的最新登录入口和注册方法,详细提供官方账号快速访问方式、网页版操作教程及安全登录技巧,帮助用户轻松管理Gmail邮箱账户,实现高效、安全的邮箱使用体验。

14

2026.02.10

铁路12306订票与退改全攻略_高效购票与座位选取技巧
铁路12306订票与退改全攻略_高效购票与座位选取技巧

本专题全面汇总铁路12306订票、退票、改签及候补订单操作技巧,提供车厢座位分布参考、抢票攻略和高铁安检注意事项,帮助新手用户快速掌握高效购票与退改流程,提高出行效率和体验。

11

2026.02.10

TensorFlow2深度学习模型实战与优化
TensorFlow2深度学习模型实战与优化

本专题面向 AI 与数据科学开发者,系统讲解 TensorFlow 2 框架下深度学习模型的构建、训练、调优与部署。内容包括神经网络基础、卷积神经网络、循环神经网络、优化算法及模型性能提升技巧。通过实战项目演示,帮助开发者掌握从模型设计到上线的完整流程。

0

2026.02.10

Vue3组合式API与组件开发实战
Vue3组合式API与组件开发实战

本专题讲解 Vue 3 组合式 API 的核心概念与应用技巧,深入分析响应式系统、生命周期管理、组件设计与复用策略。通过完整项目案例,指导前端开发者实现高性能、结构清晰的 Vue 应用,提升开发效率与代码可维护性。

4

2026.02.10

Go语言微服务架构与gRPC实战
Go语言微服务架构与gRPC实战

本专题面向有 Go 基础的开发者,系统讲解微服务架构设计与 gRPC 的高效应用。内容涵盖服务拆分、RPC 通信、负载均衡、错误处理、服务注册与发现等关键技术。通过实战案例,帮助开发者搭建高性能、可扩展的 Go 微服务系统。

1

2026.02.10

React 18状态管理与Hooks高级实践
React 18状态管理与Hooks高级实践

本专题专注于 React 18 的高级开发技术,详细讲解 useState、useEffect、useReducer、useContext 等 Hooks 的使用技巧,以及 Redux、Zustand 等状态管理工具的集成与优化方法。通过真实案例,帮助前端开发者构建可维护、性能优良的现代 React 应用。

4

2026.02.10

Node.js后端开发与Express框架实践
Node.js后端开发与Express框架实践

本专题针对初中级 Node.js 开发者,系统讲解如何使用 Express 框架搭建高性能后端服务。内容包括路由设计、中间件开发、数据库集成、API 安全与异常处理,以及 RESTful API 的设计与优化。通过实际项目演示,帮助开发者快速掌握 Node.js 后端开发流程。

2

2026.02.10

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Excel 教程
Excel 教程

共162课时 | 16.5万人学习

Pandas 教程
Pandas 教程

共15课时 | 1.1万人学习

C# 教程
C# 教程

共94课时 | 9.1万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号