十个超级有用的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) < 1  $ip == '127.0.0.1'  $ip == 'localhost')  
  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('{<li>City : ([^<]*)</li>}i', $content, $regs) )  {  
  34.             $city = $regs[1];  
  35.         }  
  36.         if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) )  {  
  37.             $state = $regs[1];  
  38.         }  
  39.  
  40.         if( $city!='' && $state!='' ){  
  41.           $location = $city . ', ' . $state;  
  42.           return $location;  
  43.         }else{  
  44.           return $default;  
  45.         }  
  46.  
  47.     } 

3. 显示网页的源代码


  1. 		<?php // display source code  
  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 #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\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<imagesx($i);$x++) {  
  4.     for ($y=0;$y<imagesy($i);$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 < 100000; $i++) {  
  8.     $array []= md5($i);  
  9. }  
  10.  
  11. // let's remove half of the array  
  12. for ($i = 0; $i < 100000; $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. 		<?php  
  2.  
  3. // Our custom error handler  
  4. function nettuts_error_handler($number, $message, $file, $line, $vars){  
  5.     $email = "  
  6.         <p>An error ($number) occurred on line  
  7.         <strong>$line</strong> and in the <strong>file: $file.</strong>  
  8.         <p> $message </p>";  
  9.  
  10.     $email .= "<pre>" . print_r($vars, 1) . "</pre>";  
  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 < 2048) ) {  
  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; 

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索array
, router
, result
, username
, password
, php代码片段
超级有用
phpstorm 代码片段、php代码片段、超级女特工酷刑片段、超级演说家精彩片段、超级演说家经典片段,以便于您获取更多的相关知识。

时间: 2024-08-03 18:06:24

十个超级有用的PHP代码片段的相关文章

又十个超级有用的PHP代码片段_php技巧

好东西要大家一起分享,上次分享了十个,这次再来十个超级有用的PHP代码片段. 1. 发送短信 调用 TextMagic API. // Include the TextMagic PHP lib require('textmagic-sms-api-php/TextMagicAPI.php'); // Set the username and password information $username = 'myusername'; $password = 'mypassword'; // C

7个有用的jQuery代码片段分享

  这篇文章主要介绍了7个有用的jQuery技巧分享,本文给出了在新窗口打开链接.设置等高的列.jQuery预加载图像.禁用鼠标右键.设定计时器等实用代码片段,需要的朋友可以参考下 jQuery是一款轻量级的JavaScript库,是最流行的客户端HTML脚本之一,它在WEB设计师和开发者中非常的有名,并且有非常多有用的插件和技术帮助WEB开发人员开发出有创意和漂亮的WEB页面. 今天我们为jQuery用户分享一些小技巧,这些技巧将帮助你提示你网站布局和应用的创意性和功能性. 一.在新窗口打开链

很有用的Jquery代码片段(转)

代码片段1: 在表单中禁用"回车键" 大家可能在表单的操作中需要防止用户意外的提交表单,那么下面这段代码肯定非常有帮助: 在线调试 在线演示 $("#form").keypress(function(e) { if (e.which == 13) { return false; }}); 代码片段2: 清除所有的表单数据 可能针对不同的表单形式,你需要调用不同类型的清楚方法,不过使用下面这个现成方法,绝对能让你省不少功夫. 在线调试 在线演示 function cl

分享几个非常有用的PHP代码片段

1. 发送短信 调用 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 =

46 个非常有用的 PHP 代码片段_php技巧

这些 PHP 片段对于 PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧- 1. 发送 SMS 在开发 Web 或者移动应用的时候,经常会遇到需要发送 SMS 给用户,或者因为登录原因,或者是为了发送信息.下面的 PHP 代码就实现了发送 SMS 的功能. 为了使用任何的语言发送 SMS,需要一个 SMS gateway.大部分的 SMS 会提供一个 API,这里是使用 MSG91 作为 SMS gateway. function send_sms($mobile,$msg) { $a

7个超级实用的PHP代码片段分享

1.超级简单的页面缓存 如果你的工程项目不是基于 CMS 系统或框架,打造一个简单的缓存系统将会非常实在.下面的代码很简单,但是对小网站而言能切切实实解决问题. <?php      // define the path and name of cached file      $cachefile = 'cached-files/'.date('M-d-Y').'.php';      // define how long we want to keep the file in seconds

7个超级实用的PHP代码片段_php技巧

1.超级简单的页面缓存 如果你的工程项目不是基于 CMS 系统或框架,打造一个简单的缓存系统将会非常实在.下面的代码很简单,但是对小网站而言能切切实实解决问题. 复制代码 代码如下: <?php // define the path and name of cached file $cachefile = 'cached-files/'.date('M-d-Y').'.php'; // define how long we want to keep the file in seconds. I

分享30个开发人员有用的CSS代码片段

CSS 是我们使用的功能强大和最常用 web 语言.他可以兼容新旧不同的浏览器,他的兼容跨度确实够大的,从微软的IE到火狐再到谷歌浏览器.在设计的时候我们总是想创建更有创意和风格的网站,无论创建怎么样的网站,有些CSS代码是必须要掌握的,可以说这是核心,掌握这样的一些CSS代码,前端布局方面基本上再不成问题,什么边框圆角,工具提示,浏览器hacks等等都不是问题. 在今天的文章中分享我收藏的 30 个CSS 代码段,无论您是经验丰富的 web 设计师还是新手,他们都是非常值得借鉴的: Css R

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

在开发网站.app或博客时,代码片段可以真正地为你节省时间.今天,我们就来分享一下我收集的一些超级有用的PHP代码片段.一起来看一看吧! 1.创建数据URI 数据URI在嵌入图像到HTML / CSS / JS中以节省HTTP请求时非常有用,并且可以减少网站的加载时间.下面的函数可以创建基于$file的数据URI. function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode