19个超实用的PHP代码片段

每位程序员和开发者都喜欢讨论他们最爱的代码片段,尤其是当PHP开发者花费数个小时为网页编码或创建应用时,他们更知道这些代码的重要性。为了节约编码时间,小编收集了一些较为实用的代码片段,帮助开发者提高工作效率。

1) Whois query using PHP ——利用PHP获取Whois请求

利用这段代码,在特定的域名里可获得whois信息。把域名名称作为参数,并显示所有域名的相关信息,代码如下:

  1. function whois_query($domain) {
  2. // fix the domain name:
  3. $domain = strtolower(trim($domain));
  4. $domain = preg_replace('/^http:\/\//i', '', $domain);
  5. $domain = preg_replace('/^www\./i', '', $domain);
  6. $domain = explode('/', $domain);
  7. $domain = trim($domain[0]);
  8. // split the TLD from domain name
  9. $_domain = explode('.', $domain);
  10. $lst = count($_domain)-1;
  11. $ext = $_domain[$lst];
  12. // You find resources and lists
  13. // like these on wikipedia:
  14. //
  15. // <a href="http://de.wikipedia.org/wiki/Whois">http://de.wikipedia.org/wiki/Whois</a>
  16. //
  17. $servers = array(
  18. "biz" => "whois.neulevel.biz",
  19. "com" => "whois.internic.net",
  20. "us" => "whois.nic.us",
  21. "coop" => "whois.nic.coop",
  22. "info" => "whois.nic.info",
  23. "name" => "whois.nic.name",
  24. "net" => "whois.internic.net",
  25. "gov" => "whois.nic.gov",
  26. "edu" => "whois.internic.net",
  27. "mil" => "rs.internic.net",
  28. "int" => "whois.iana.org",
  29. "ac" => "whois.nic.ac",
  30. "ae" => "whois.uaenic.ae",
  31. "at" => "whois.ripe.net",
  32. "au" => "whois.aunic.net",
  33. "be" => "whois.dns.be",
  34. "bg" => "whois.ripe.net",
  35. "br" => "whois.registro.br",
  36. "bz" => "whois.belizenic.bz",
  37. "ca" => "whois.cira.ca",
  38. "cc" => "whois.nic.cc",
  39. "ch" => "whois.nic.ch",
  40. "cl" => "whois.nic.cl",
  41. "cn" => "whois.cnnic.net.cn",
  42. "cz" => "whois.nic.cz",
  43. "de" => "whois.nic.de",
  44. "fr" => "whois.nic.fr",
  45. "hu" => "whois.nic.hu",
  46. "ie" => "whois.domainregistry.ie",
  47. "il" => "whois.isoc.org.il",
  48. "in" => "whois.ncst.ernet.in",
  49. "ir" => "whois.nic.ir",
  50. "mc" => "whois.ripe.net",
  51. "to" => "whois.tonic.to",
  52. "tv" => "whois.tv",
  53. "ru" => "whois.ripn.net",
  54. "org" => "whois.pir.org",
  55. "aero" => "whois.information.aero",
  56. "nl" => "whois.domain-registry.nl"
  57. );
  58. if (!isset($servers[$ext])){
  59. die('Error: No matching nic server found!');
  60. }
  61. $nic_server = $servers[$ext];
  62. $output = '';
  63. // connect to whois server:
  64. if ($conn = fsockopen ($nic_server, 43)) {
  65. fputs($conn, $domain."\r\n");
  66. while(!feof($conn)) {
  67. $output .= fgets($conn,128);
  68. }
  69. fclose($conn);
  70. }
  71. else { die('Error: Could not connect to ' . $nic_server . '!'); }
  72. return $output;
  73. }

2) Text messaging with PHP using the TextMagic API ——使用TextMagic API 获取PHP Test信息

TextMagic引入强大的核心API,可轻松将SMS发送到手机,该API是需要付费,代码如下:

  1. the TextMagic PHP lib
  2. require('textmagic-sms-api-php/TextMagicAPI.php');
  3. // Set the username and password information
  4. $username = 'myusername';
  5. $password = 'mypassword';
  6. // Create a new instance of TM
  7. $router = new TextMagicAPI(array(
  8. 'username' => $username,
  9. 'password' => $password
  10. ));
  11. // Send a text message to '999-123-4567'
  12. $result = $router->send('Wake up!', array(9991234567), true);
  13. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

3) Get info about your memory usage——获取内存使用率

这段代码帮助你获取内存使用率,代码如下:

  1. echo "Initial: ".memory_get_usage()." bytes \n";
  2. /* prints
  3. Initial: 361400 bytes
  4. */
  5. // let's use up some memory
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // let's remove half of the array
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo "Final: ".memory_get_usage()." bytes \n";
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo "Peak: ".memory_get_peak_usage()." bytes \n";
  18. /* prints
  19. Peak: 13687072 bytes
  20. */

4) Display source code of any webpage——查看任意网页源代码

如果你想查看网页源代码,那么只需更改第二行的URL,源代码就会在网页上显示出,代码如下:

  1. <?php // display source code $lines = file('http://google.com/'); foreach ($lines as $line_num => $line) {
  2. // loop thru each line and prepend line numbers
  3. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
  4. \n";
  5. }

5) Create data uri's——创建数据uri

通过使用此代码,你可以创建数据Uri,这对在HTML/CSS中嵌入图片非常有用,可帮助节省HTTP请求,代码如下:

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

6) Detect location by IP——通过IP检索出地理位置

这段代码帮助你查找特定的IP,只需在功能参数上输入IP,就可检测出位置,代码如下:

  1. function detect_city($ip) {
  2. $default = 'UNKNOWN';
  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=' . 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://' . $_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; } }

7) Detect browser language——查看浏览器语言

检测浏览器使用的代码脚本语言,代码如下:

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

8) Check if server is HTTPS——检测服务器是否是HTTPS,代码如下:

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

9) Generate CSV file from a PHP array——在PHP数组中生成.csv 文件,代码如下:

  1. function generateCsv($data, $delimiter = ',', $enclosure = '"') {
  2. $handle = fopen('php://temp', 'r+');
  3. foreach ($data as $line) {
  4. fputcsv($handle, $line, $delimiter, $enclosure);
  5. }
  6. rewind($handle);
  7. while (!feof($handle)) {
  8. $contents .= fread($handle, 8192);
  9. }
  10. fclose($handle);
  11. return $contents;
  12. }

10.查找Longitudes与Latitudes之间的距离,代码如下:

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

The example returns the following:

  1. miles: 2.6025
  2. feet: 13,741.4350
  3. yards: 4,580.4783
  4. kilometers: 4.1884
  5. meters: 4,188.3894

11.完善cURL功能,代码如下:

  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(!emptyempty($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(!emptyempty($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. }
  25. }

12.清理用户输入,代码如下:

  1. <?php
  2. function cleanInput($input) {
  3. $search = array(
  4. '@<script[^>]*?>.*?</script>@si', // Strip out javascript
  5. '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
  6. '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
  7. '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
  8. );
  9. $output = preg_replace($search, '', $input);
  10. return $output;
  11. }
  12. ?>
  13. <?php
  14. function sanitize($input) {
  15. if (is_array($input)) {
  16. foreach($input as $var=>$val) {
  17. $output[$var] = sanitize($val);
  18. }
  19. }
  20. else {
  21. if (get_magic_quotes_gpc()) {
  22. $input = stripslashes($input);
  23. }
  24. $input = cleanInput($input);
  25. $output = mysql_real_escape_string($input);
  26. }
  27. return $output;
  28. }
  29. ?>

13.通过IP(城市、国家)检测地理位置,代码如下:

  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=' . 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://' . $_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; } }

14.设置密码强度,代码如下:

  1. function password_strength($string){
  2. $h = 0;
  3. $size = strlen($string);
  4. foreach(count_chars($string, 1) as $v){
  5. $p = $v / $size;
  6. $h -= $p * log($p) / log(2);
  7. }
  8. $strength = ($h / 4) * 100;
  9. if($strength > 100){
  10. $strength = 100;
  11. }
  12. return $strength;
  13. }
  14. var_dump(password_strength("Correct Horse Battery Staple"));
  15. echo "<br>";
  16. var_dump(password_strength("Super Monkey Ball"));
  17. echo "<br>";
  18. var_dump(password_strength("Tr0ub4dor&3"));
  19. echo "<br>";
  20. var_dump(password_strength("abc123"));
  21. echo "<br>";
  22. var_dump(password_strength("sweet"));

15.检测浏览器语言,只提供可用的$availableLanguages作为数组(‘en', ‘de', ‘es'),代码如下:

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

16.创建数据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. }

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

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

代码如下:

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

18.终极加密功能,代码如下:

  1. // f(ucking) u(ncrackable) e(ncryption) function by BlackHatDBL (www.phpfensi.com)
  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;
  18. }

19a.Tweeter Feed Runner——使用任意twitter名,可在任意页面上加载用户资源,代码如下:

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

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

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