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


Posted in PHP onSeptember 24, 2015

好东西要大家一起分享,上次分享了十个,这次再来十个超级有用的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 = 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查找地址

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('{<li>City : ([^<]*)</li>}i', $content, $regs) ) { 
   $city = $regs[1]; 
  } 
  if ( preg_match('{<li>State/Province : ([^<]*)</li>}i', $content, $regs) ) { 
   $state = $regs[1]; 
  } 
 
  if( $city!='' && $state!='' ){ 
   $location = $city . ', ' . $state; 
   return $location; 
  }else{ 
   return $default; 
  } 
 
 }

3. 显示网页的源代码

<?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 #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n"; 
}
4. 检查服务器是否使用HTTPS

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

5. 显示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. 获取内存使用信息

echo "Initial: ".memory_get_usage()." bytes \n"; 
/* prints 
Initial: 361400 bytes 
*/ 
 
// let's use up some memory 
for ($i = 0; $i < 100000; $i++) { 
 $array []= md5($i); 
} 
 
// let'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 = 
"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检查

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: 
 // 
 // 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('Error: No matching nic server found!'); 
 } 
 
 $nic_server = $servers[$ext]; 
 
 $output = ''; 
 
 // 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('Error: Could not connect to ' . $nic_server . '!'); } 
 
 return $output; 
}

10. 通过Email发送PHP错误

<?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>" . print_r($vars, 1) . "</pre>"; 
 
 $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 < 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;

是不是也很精彩,和之前的一起收藏吧

PHP 相关文章推荐
PHP编程网上资源导航
Oct 09 PHP
DISCUZ 分页代码
Jan 02 PHP
php 禁止页面缓存输出
Jan 07 PHP
php数组的概述及分类与声明代码演示
Feb 26 PHP
php获取Google机器人访问足迹的方法
Apr 15 PHP
PHP实现获取文件后缀名的几种常用方法
Aug 08 PHP
PHP获取二维数组中某一列的值集合
Dec 25 PHP
php实现等比例不失真缩放上传图片的方法
Nov 14 PHP
微信公众号开发之通过接口删除菜单
Feb 20 PHP
PHP批量修改文件名称的方法分析
Feb 27 PHP
php中curl和soap方式请求服务超时问题的解决
Jun 11 PHP
php 使用 __call实现重载功能示例
Nov 18 PHP
PHP易混淆知识整理笔记
Sep 24 #PHP
PHP直接修改表内容DataGrid功能实现代码
Sep 24 #PHP
PHP生成条形码大揭秘
Sep 24 #PHP
php商品对比功能代码分享
Sep 24 #PHP
php实现简易聊天室应用代码
Sep 23 #PHP
利用PHP如何实现Socket服务器
Sep 23 #PHP
10个超级有用的PHP代码片段果断收藏
Sep 23 #PHP
You might like
PHP在获取指定目录下的目录,在获取的目录下面再创建文件,多平台
2011/08/03 PHP
PHP定时更新程序设计思路分享
2014/06/10 PHP
javascript学习笔记(五) Array 数组类型介绍
2012/06/19 Javascript
JavaScript建立一个语法高亮输入框实现思路
2013/02/26 Javascript
JavaScript的继承的封装介绍
2013/10/15 Javascript
Javascript模仿淘宝信用评价实例(附源码)
2015/11/26 Javascript
微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传
2017/04/18 Javascript
前端开发不得不知的10个最佳ES6特性
2017/08/30 Javascript
浅谈webpack打包过程中因为图片的路径导致的问题
2018/02/21 Javascript
JavaScript DOM元素常见操作详解【添加、删除、修改等】
2018/05/09 Javascript
ES6基础之字符串和函数的拓展详解
2019/08/22 Javascript
JavaScript基于面向对象实现的无缝滚动轮播示例
2020/01/17 Javascript
解决vue axios跨域 Request Method: OPTIONS问题(预检请求)
2020/08/14 Javascript
vue-cli 关闭热更新操作
2020/09/18 Javascript
[47:52]完美世界DOTA2联赛PWL S2 PXG vs InkIce 第二场 11.26
2020/11/30 DOTA
[22:07]DOTA2-DPC中国联赛 正赛 iG vs Magma 选手采访
2021/03/11 DOTA
python 动态获取当前运行的类名和函数名的方法
2014/04/15 Python
Python实现一个转存纯真IP数据库的脚本分享
2017/05/21 Python
对python中使用requests模块参数编码的不同处理方法
2018/05/18 Python
python得到单词模式的示例
2018/10/15 Python
python自定义函数实现最大值的输出方法
2019/07/09 Python
python实现证件照换底功能
2019/08/20 Python
Pandas DataFrame中的tuple元素遍历的实现
2019/10/23 Python
Python使用tkinter制作在线翻译软件
2021/02/22 Python
附答案的Java面试题
2012/11/19 面试题
高中自我鉴定范文
2013/11/03 职场文书
学校课外活动总结
2014/05/08 职场文书
鼓舞士气的口号
2014/06/16 职场文书
学校安全教育月活动总结
2014/07/07 职场文书
学校端午节活动方案
2014/08/23 职场文书
争做文明公民倡议书
2014/08/29 职场文书
四风问题党员个人整改措施
2014/10/27 职场文书
红色革命电影观后感
2015/06/18 职场文书
《世界多美呀》教学反思
2016/02/22 职场文书
创新创业项目计划书该怎样写?
2019/08/13 职场文书
关于PostgreSQL JSONB的匹配和交集问题
2021/09/14 PostgreSQL