热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

又十个超级有用的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'; 
 
// 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&#63;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('{
  • City : ([^<]*)
  • }i', $content, $regs) ) { $city = $regs[1]; } if ( preg_match('{
  • State/Province : ([^<]*)
  • }i', $content, $regs) ) { $state = $regs[1]; } if( $city!='' && $state!='' ){ $location = $city . ', ' . $state; return $location; }else{ return $default; } }

    3. 显示网页的源代码

    <&#63;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 #{$line_num} : " . htmlspecialchars($line) . "
    \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> 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错误

    <&#63;php 
     
    // Our custom error handler 
    function nettuts_error_handler($number, $message, $file, $line, $vars){ 
     $email = " 
      

    An error ($number) occurred on line $line and in the file: $file.

    $message

    "; $email .= "
    " . 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 <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;

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


    推荐阅读
    • React 小白初入门
      推荐学习:React官方文档:https:react.docschina.orgReact菜鸟教程:https:www.runoob.c ... [详细]
    • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
    • OAuth2.0指南
      引言OAuth2.0是一种应用之间彼此访问数据的开源授权协议。比如,一个游戏应用可以访问Facebook的用户数据,或者一个基于地理的应用可以访问Foursquare的用户数据等。 ... [详细]
    • 知识图谱——机器大脑中的知识库
      本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
    • 分享css中提升优先级属性!important的用法总结
      web前端|css教程css!importantweb前端-css教程本文分享css中提升优先级属性!important的用法总结微信门店展示源码,vscode如何管理站点,ubu ... [详细]
    • 本文介绍了如何使用jQuery和AJAX来实现动态更新两个div的方法。通过调用PHP文件并返回JSON字符串,可以将不同的文本分别插入到两个div中,从而实现页面的动态更新。 ... [详细]
    • Hadoop源码解析1Hadoop工程包架构解析
      1 Hadoop中各工程包依赖简述   Google的核心竞争技术是它的计算平台。Google的大牛们用了下面5篇文章,介绍了它们的计算设施。   GoogleCluster:ht ... [详细]
    • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
    • 禁止程序接收鼠标事件的工具_VNC Viewer for Mac(远程桌面工具)免费版
      VNCViewerforMac是一款运行在Mac平台上的远程桌面工具,vncviewermac版可以帮助您使用Mac的键盘和鼠标来控制远程计算机,操作简 ... [详细]
    • Windows下配置PHP5.6的方法及注意事项
      本文介绍了在Windows系统下配置PHP5.6的步骤及注意事项,包括下载PHP5.6、解压并配置IIS、添加模块映射、测试等。同时提供了一些常见问题的解决方法,如下载缺失的msvcr110.dll文件等。通过本文的指导,读者可以轻松地在Windows系统下配置PHP5.6,并解决一些常见的配置问题。 ... [详细]
    • 推荐系统遇上深度学习(十七)详解推荐系统中的常用评测指标
      原创:石晓文小小挖掘机2018-06-18笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值, ... [详细]
    • CSS|网格-行-结束属性原文:https://www.gee ... [详细]
    • 篇首语:本文由编程笔记#小编为大家整理,主要介绍了Flutter添加APP启动StoryView相关的知识,希望对你有一定的参考价值。 ... [详细]
    • 都说Python处理速度慢,为何月活7亿的 Instagram依然在使用Python?
      点击“Python编程与实战”,选择“置顶公众号”第一时间获取Python技术干货!来自|简书作者|我爱学python链接|https:www.jian ... [详细]
    • JavaScript和Python是用于构建各种应用程序的两种有影响力的编程语言。尽管JavaScript多年来一直是占主导地位的编程语言,但Python的迅猛发展有 ... [详细]
    author-avatar
    一季花落的秋天_981
    这个家伙很懒,什么也没留下!
    PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
    Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有