直接拿来用,九个超实用的PHP代码片段

http://www.csdn.net/article/2013-11-01/2817365-useful-snippets-for-php-developers

http://www.csdn.net/article/2013-07-23/2816316-10-php-snippets-for-developers

 

一、查看邮件是否已被阅读

当你在发送邮件时,你或许很想知道该邮件是否被对方已阅读。这里有段非常有趣的代码片段能够显示对方IP地址记录阅读的实际日期和时间。

[js] view plaincopy

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

源码

二、从网页中提取关键字

一段伟大的代码片段能够轻松的从网页中提取关键字。

[js] view plaincopy

  1. $meta = get_meta_tags(‘http://www.emoticode.net/&#8217;);  
  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. print_r( $keywords ); 

源码

三、查找页面上的所有链接

使用DOM,你可以轻松从任何页面上抓取链接,代码示例如下:

[js] view plaincopy

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

源码

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

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

[js] view plaincopy

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

源码

五、创建数据URL

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

[js] view plaincopy

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

源码

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

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

[js] view plaincopy

  1. $image = file_get_contents(‘http://www.url.com/image.jpg&#8217;);  
  2. file_put_contents(‘/images/image.jpg’, $image); //Where to save the image

源码

七、移除Remove Microsoft Word HTML Tag

当你使用Microsoft Word会创建许多Tag,比如font,span,style,class等。这些标签对于Word本身而言是非常有用的,但是当你从Word粘贴至网页时,你会发现很多无用的Tag。因此,下面的这段代码可帮助你删除所有无用的Word HTML Tag。

[js] view plaincopy

  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. $html = ereg_replace(“<(/)?(font|span|del|ins)[^>]*>”,””,$html);  
  8. // then run another pass over the html (twice), removing unwanted attributes
  9. $html = ereg_replace(“<([^>]*)(class|lang|style|size|face)=(“[^”]*”|'[^’]*’|[^>]+)([^>]*)>”,”<\1>”,$html);  
  10. $html = ereg_replace(“<([^>]*)(class|lang|style|size|face)=(“[^”]*”|'[^’]*’|[^>]+)([^>]*)>”,”<\1>”,$html);  
  11. return $html  

源码

八、检测浏览器语言

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

[js] view plaincopy

  1. function get_client_language($availableLanguages, $default=’en’){  
  2. if (isset($_SERVER[‘HTTP_ACCEPT_LANGUAGE’])) {  
  3.         $langs=explode(‘,’,$_SERVER[‘HTTP_ACCEPT_LANGUAGE’]);  
  4.         foreach ($langs as $value){  
  5.             $choice=substr($value,0,2);  
  6. if(in_array($choice, $availableLanguages)){  
  7. return $choice;  
  8.             }  
  9.         }  
  10.     }   
  11. return $default;  

源码

九、显示Facebook 粉丝数量

如果你的网站或者博客上有内链的Facebook页面,你或许想知道拥有多少粉丝。这段代码将帮助你查看Facebook粉丝数,记住,别忘了在你的页面ID第二行添加该段代码。

[js] view plaincopy

  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=&#8221;.$page_id.””) or die (“a lot”);  
  4.     $fans = $xml->page->fan_count;  
  5.     echo $fans;  
  6. ?> 

源码

 

PHP是一种HTML内嵌式的语言,是一种在服务器端执行的嵌入HTML文档的脚本语言。PHP拥有数以百计的基本功能,支持上千种扩展。这些功能都被很好的加载在PHP站点上,但内置的库有各种各样的命名。在PHP代码库中包含了无数个有用的PHP代码片段,每位开发者都需要不断完善自己的“工具箱”。有了这些代码片段可以为你节省大量的时间,一起来看下。

1.查找Longitudes与Latitudes之间的距离

[js] view plaincopy

  1. function getDistanceBetweenPointsNew($latitude1, $longitude1, $latitude2, $longitude2) {  
  2.     $theta = $longitude1 – $longitude2;  
  3.     $miles = (sin(deg2rad($latitude1)) * sin(deg2rad($latitude2))) + (cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta)));  
  4.     $miles = acos($miles);  
  5.     $miles = rad2deg($miles);  
  6.     $miles = $miles * 60 * 1.1515;  
  7.     $feet = $miles * 5280;  
  8.     $yards = $feet / 3;  
  9.     $kilometers = $miles * 1.609344;  
  10.     $meters = $kilometers * 1000;  
  11. return compact(‘miles’,’feet’,’yards’,’kilometers’,’meters’);   
  12. }  
  13. $point1 = array(‘lat’ => 40.770623, ‘long’ => -73.964367);  
  14. $point2 = array(‘lat’ => 40.758224, ‘long’ => -73.917404);  
  15. $distance = getDistanceBetweenPointsNew($point1[‘lat’], $point1[‘long’], $point2[‘lat’], $point2[‘long’]);  
  16. foreach ($distance as $unit => $value) {  
  17.     echo $unit.’: ‘.number_format($value,4).’  
  18. ‘;  
  19. }  
  20. The example returns the following:  
  21. miles: 2.6025  
  22. feet: 13,741.4350  
  23. yards: 4,580.4783  
  24. kilometers: 4.1884  
  25. meters: 4,188.3894 

源码

2.完善cURL功能

[js] view plaincopy

  1. function xcurl($url,$ref=null,$post=array(),$ua=”Mozilla/5.0 (X11; Linux x86_64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre”,$print=false) {  
  2.     $ch = curl_init();  
  3.     curl_setopt($ch, CURLOPT_AUTOREFERER, true);  
  4. if(!empty($ref)) {  
  5.         curl_setopt($ch, CURLOPT_REFERER, $ref);  
  6.     }  
  7.     curl_setopt($ch, CURLOPT_URL, $url);  
  8.     curl_setopt($ch, CURLOPT_HEADER, 0);  
  9.     curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);  
  10.     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
  11. if(!empty($ua)) {  
  12.         curl_setopt($ch, CURLOPT_USERAGENT, $ua);  
  13.     }  
  14. if(count($post) > 0){  
  15.         curl_setopt($ch, CURLOPT_POST, 1);  
  16.         curl_setopt($ch, CURLOPT_POSTFIELDS, $post);      
  17.     }  
  18.     $output = curl_exec($ch);  
  19.     curl_close($ch);  
  20. if($print) {  
  21.         print($output);  
  22.     } else {  
  23. return $output;  
  24.     }  

源码

3.清理用户输入

[js] view plaincopy

  1. ]*?>.*?@si’,   // Strip out javascript
  2. ‘@<[\/\!]*?[^<>]*?>@si’,            // Strip out HTML tags
  3. ‘@]*?>.*?@siU’,    // Strip style tags properly
  4. ‘@@’ // Strip multi-line comments
  5.   );  
  6.     $output = preg_replace($search, ”, $input);  
  7. return $output;  
  8.   }  
  9. ?>  
  10. $val) {  
  11.             $output[$var] = sanitize($val);  
  12.         }  
  13.     }  
  14. else {  
  15. if (get_magic_quotes_gpc()) {  
  16.             $input = stripslashes($input);  
  17.         }  
  18.         $input  = cleanInput($input);  
  19.         $output = mysql_real_escape_string($input);  
  20.     }  
  21. return $output;  
  22. }  
  23. ?> 

源码

4.通过IP(城市、国家)检测地理位置

[js] view plaincopy

  1. function detect_city($ip) {  
  2.         $default = ‘Hollywood, CA’;  
  3. 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=&#8217; . urlencode($ip);         $ch = curl_init();           $curl_opt = array(             CURLOPT_FOLLOWLOCATION  => 1,  
  4.             CURLOPT_HEADER      => 0,  
  5.             CURLOPT_RETURNTRANSFER  => 1,  
  6.             CURLOPT_USERAGENT   => $curlopt_useragent,  
  7.             CURLOPT_URL       => $url,  
  8.             CURLOPT_TIMEOUT         => 1,  
  9.             CURLOPT_REFERER         => ‘http://&#8217; . $_SERVER[‘HTTP_HOST’],  
  10.         );  
  11.         curl_setopt_array($ch, $curl_opt);  
  12.         $content = curl_exec($ch);  
  13. if (!is_null($curl_info)) {  
  14.             $curl_info = curl_getinfo($ch);  
  15.         }  
  16.         curl_close($ch);  
  17. if ( preg_match(‘{  
  18. City : ([^<]*)  
  19. }i’, $content, $regs) ) { $city = $regs[1]; } if ( preg_match(‘{  
  20. State/Province : ([^<]*)  
  21. }i’, $content, $regs) ) { $state = $regs[1]; } if( $city!=” && $state!=” ){ $location = $city . ‘, ‘ . $state; return $location; }else{ return $default; } } 

源码

5.设置密码强度

[js] view plaincopy

  1. 100){   
  2.         $strength = 100;   
  3.     }   
  4. return $strength;   
  5. }   
  6. var_dump(password_strength(“Correct Horse Battery Staple”));   
  7. echo ”  
  8. “;   
  9. var_dump(password_strength(“Super Monkey Ball”));   
  10. echo ”  
  11. “;   
  12. var_dump(password_strength(“Tr0ub4dor&3”));   
  13. echo ”  
  14. “;   
  15. var_dump(password_strength(“abc123”));   
  16. echo ”  
  17. “;   
  18. var_dump(password_strength(“sweet”)); 

源码

6.检测浏览器语言,只提供可用的$availableLanguages作为数组(‘en’, ‘de’, ‘es’)

[js] view plaincopy

  1. function get_client_language($availableLanguages, $default=’en’){  
  2. if (isset($_SERVER[‘HTTP_ACCEPT_LANGUAGE’])) {  
  3.         $langs=explode(‘,’,$_SERVER[‘HTTP_ACCEPT_LANGUAGE’]);  
  4. //start going through each one
  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;  

源码

7.创建数据URL

[js] view plaincopy

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

源码

8.创建更加友好的页面标题SEO URL

输入示例:$title = “This foo’s bar is rockin’ cool!”; echo makeseoname($title); //RETURNS: //this-foos-bar-is-rockin-cool

[js] view plaincopy

  1. function make_seo_name($title) {  
  2. return preg_replace(‘/[^a-z0-9_-]/i’, ”, strtolower(str_replace(‘ ‘, ‘-‘, trim($title))));  

源码

9.终极加密功能

[js] view plaincopy

  1. // f(ucking) u(ncrackable) e(ncryption) function by BlackHatDBL (www.netforme.net)
  2. function fue($hash,$times) {  
  3. // Execute the encryption(s) as many times as the user wants
  4. for($i=$times;$i>0;$i–) {  
  5. // Encode with base64…
  6.         $hash=base64_encode($hash);  
  7. // and md5…
  8.         $hash=md5($hash);  
  9. // sha1…
  10.         $hash=sha1($hash);  
  11. // sha256… (one more)
  12.         $hash=hash(“sha256”, $hash);  
  13. // sha512
  14.         $hash=hash(“sha512”, $hash);  
  15.     }  
  16. // Finaly, when done, return the value
  17. return $hash;  

源码

10a.Tweeter Feed Runner——使用任意twitter名,可在任意页面上加载用户资源。

[js] view plaincopy

  1. pversion;   
  2.     }   
  3. public function loadTimeline($user, $max = 20){   
  4.         $this->twitURL .= ‘statuses/user_timeline.xml?screen_name=’.$user.’&count=’.$max;   
  5.         $ch        = curl_init();   
  6.         curl_setopt($ch, CURLOPT_URL, $this->twitURL);   
  7.         curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);   
  8.         $this->xml = curl_exec($ch);   
  9. return $this;   
  10.     }   
  11. public function getTweets(){   
  12.         $this->twitterArr = $this->getTimelineArray();   
  13.         $tweets = array();   
  14.         foreach($this->twitterArr->status as $status){   
  15.             $tweets[$status->created_at->__toString()] = $status->text->__toString();   
  16.         }   
  17. return $tweets;   
  18.     }   
  19. public function getTimelineArray(){   
  20. return simplexml_load_string($this->xml);   
  21.     }   
  22. public function formatTweet($tweet){   
  23.         $tweet = preg_replace(“/(http(.+?))( |$)/”,”$1$3″, $tweet);   
  24.         $tweet = preg_replace(“/#(.+?)(\h|\W|$)/”, “#$1$2”, $tweet);   
  25.         $tweet = preg_replace(“/@(.+?)(\h|\W|$)/”, “@$1$2”, $tweet);   
  26. return $tweet;   
  27.     }   

10b. Tweeter Feed Runner——用于在主题中创建文件,比如:example.php

[js] view plaincopy

  1. loadTimeline(“phpsnips”)->getTweets();   
  2. foreach($feed as $time => $message){   
  3.     echo “<div class=’tweet’>”.$twitter->formatTweet($message).”<br />At: “.$time.”</div>”;   

源码

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s