超实用的PHP代码片段

一、查看邮件是否已被阅

  1. <?  
  2. error_reporting(0);  
  3. Header("Content-Type: image/jpeg");  
  4.   
  5. //Get IP  
  6. if (!empty($_SERVER['HTTP_CLIENT_IP']))  
  7. {  
  8.   $ip=$_SERVER['HTTP_CLIENT_IP'];  
  9. }  
  10. elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))  
  11. {  
  12.   $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];  
  13. }  
  14. else  
  15. {  
  16.   $ip=$_SERVER['REMOTE_ADDR'];  
  17. }  
  18.   
  19. //Time  
  20. $actual_time = time();  
  21. $actual_day = date('Y.m.d', $actual_time);  
  22. $actual_day_chart = date('d/m/y', $actual_time);  
  23. $actual_hour = date('H:i:s', $actual_time);  
  24.   
  25. //GET Browser  
  26. $browser = $_SERVER['HTTP_USER_AGENT'];  
  27.       
  28. //LOG  
  29. $myFile = "log.txt";  
  30. $fh = fopen($myFile, 'a+');  
  31. $stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n";  
  32. fwrite($fh, $stringData);  
  33. fclose($fh);  
  34.   
  35. //Generate Image (Es. dimesion is 1x1)  
  36. $newimage = ImageCreate(1,1);  
  37. $grigio = ImageColorAllocate($newimage,255,255,255);  
  38. ImageJPEG($newimage);  
  39. ImageDestroy($newimage);  
  40.       
  41. ?>  
二、从网页中提取关键字

  1. $meta = get_meta_tags('http://www.emoticode.net/');  
  2. $keywords = $meta['keywords'];  
  3. // Split keywords  
  4. $keywords = explode(',', $keywords );  
  5. // Trim them  
  6. $keywords = array_map( 'trim', $keywords );  
  7. // Remove empty values  
  8. $keywords = array_filter( $keywords );  
  9.   
  10. print_r( $keywords );  
三、查找页面上的所有链接

  1. $html = file_get_contents('http://www.example.com');  
  2.   
  3. $dom = new DOMDocument();  
  4. @$dom->loadHTML($html);  
  5.   
  6. // grab all the on the page  
  7. $xpath = new DOMXPath($dom);  
  8. $hrefs = $xpath->evaluate("/html/body//a");  
  9.   
  10. for ($i = 0; $i < $hrefs->length; $i++) {  
  11.        $href = $hrefs->item($i);  
  12.        $url = $href->getAttribute('href');  
  13.        echo $url.'<br />';  
  14. }  

四、自动转换URL,跳转至超链接

在WordPress中,如果你想自动转换URL,跳转至超链接页面,你可以利用内置的函数make_clickable()执行此操作。如果你想基于WordPress之外操作该程序,那么你可以参考wp-includes/formatting.php源代码。 

  1. function _make_url_clickable_cb($matches) {  
  2.     $ret = '';  
  3.     $url = $matches[2];  
  4.    
  5.     if ( empty($url) )  
  6.         return $matches[0];  
  7.     // removed trailing [.,;:] from URL  
  8.     if ( in_array(substr($url, -1), array('.'','';'':')) === true ) {  
  9.         $ret = substr($url, -1);  
  10.         $url = substr($url, 0, strlen($url)-1);  
  11.     }  
  12.     return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;  
  13. }  
  14.    
  15. function _make_web_ftp_clickable_cb($matches) {  
  16.     $ret = '';  
  17.     $dest = $matches[2];  
  18.     $dest = 'http://' . $dest;  
  19.    
  20.     if ( empty($dest) )  
  21.         return $matches[0];  
  22.     // removed trailing [,;:] from URL  
  23.     if ( in_array(substr($dest, -1), array('.'','';'':')) === true ) {  
  24.         $ret = substr($dest, -1);  
  25.         $dest = substr($dest, 0, strlen($dest)-1);  
  26.     }  
  27.     return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;  
  28. }  
  29.    
  30. function _make_email_clickable_cb($matches) {  
  31.     $email = $matches[2] . '@' . $matches[3];  
  32.     return $matches[1] . "<a href=\"mailto:$email\">$email</a>";  
  33. }  
  34.    
  35. function make_clickable($ret) {  
  36.     $ret = ' ' . $ret;  
  37.     // in testing, using arrays here was found to be faster  
  38.     $ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is''_make_url_clickable_cb', $ret);  
  39.     $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is''_make_web_ftp_clickable_cb', $ret);  
  40.     $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i''_make_email_clickable_cb', $ret);  
  41.    
  42.     // this one is not in an array because we need it to run last, for cleanup of accidental links within links  
  43.     $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i""$1$3</a>", $ret);  
  44.     $ret = trim($ret);  
  45.     return $ret;  
  46. }  

五、创建数据URL

数据URL可以直接嵌入到HTML/CSS/JS中,以节省大量的 HTTP请求。 下面的这段代码可利用$file轻松创建数据URL。 

  1. function data_uri($file, $mime) {  
  2.   $contents=file_get_contents($file);  
  3.   $base64=base64_encode($contents);  
  4.   echo "data:$mime;base64,$base64";  
  5. }  

六、从服务器上下载&保存一个远程图片 

当你在搭建网站时,从远程服务器下载某张图片并且将其保存在自己的服务器上,这一操作会经常用到。代码如下:

  1. $image = file_get_contents('http://www.url.com/image.jpg');  
  2. file_put_contents('/images/image.jpg', $image); //Where to save the image  
七、移除Remove Microsoft Word HTML Tag

  1. function cleanHTML($html) {  
  2. /// <summary>  
  3. /// Removes all FONT and SPAN tags, and all Class and Style attributes.  
  4. /// Designed to get rid of non-standard Microsoft Word HTML tags.  
  5. /// </summary>  
  6. // start by completely removing all unwanted tags  
  7.   
  8. $html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html);  
  9.   
  10. // then run another pass over the html (twice), removing unwanted attributes  
  11.   
  12. $html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);  
  13. $html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html);  
  14.   
  15. return $html  
  16. }  

八、检测浏览器语言

如果你的网站上有多种语言,那么可以使用这段代码作为默认的语言来检测浏览器语言。该段代码将返回浏览器客户端使用的初始语言。 

  1. function get_client_language($availableLanguages, $default='en'){  
  2.     if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {  
  3.         $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);  
  4.   
  5.         foreach ($langs as $value){  
  6.             $choice=substr($value,0,2);  
  7.             if(in_array($choice, $availableLanguages)){  
  8.                 return $choice;  
  9.             }  
  10.         }  
  11.     }   
  12.     return $default;  
九、显示Facebook 粉丝数量
  1. <?php  
  2.     $page_id = "YOUR PAGE-ID";  
  3.     $xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");  
  4.     $fans = $xml->page->fan_count;  
  5.     echo $fans;  
  6. ?>  

更多代码请参考:http://www.emoticode.net/




通过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.         }  

  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";    
  6. }   

判断服务器是否是HTTPS连接

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

了解你的内存使用情况

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

使用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);  

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

 不显示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;    

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值