首页 > 开发 > PHP > 正文

非常有用的9个PHP代码片段

2024-05-04 22:01:37
字体:大 中 小
来源:转载
供稿:网友

本文我们就来分享一下我收集的一些超级有用的PHP代码片段。一起来看一看吧!

1.创建数据URI

数据URI在嵌入图像到HTML / CSS / JS中以节省HTTP请求时非常有用,并且可以减少网站的加载时间。下面的函数可以创建基于$file的数据URI。

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

2.合并JavaScript和CSS文件

另一个可以尽量减少HTTP请求和节省页面加载时间的好建议是:合并你的CSS和JS文件。虽然我更建议大家使用专用插件(例如minify),但使用PHP来合并文件也非常容易。我们来看一下:

  1. function combine_my_files($array_files, $destination_dir, $dest_file_name){ 
  2.  
  3.  if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist 
  4.  
  5.  $content = ""; 
  6.  
  7.  foreach ($array_files as $file){ //loop through array list 
  8.  
  9.  $content .= file_get_contents($file); //read each file 
  10.  
  11.  } 
  12.  
  13.  //You can use some sort of minifier here 
  14.  
  15.  //minify_my_js($content); 
  16.  
  17.  $new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing 
  18.  
  19.  fwrite($new_file , $content); //write to destination 
  20.  
  21.  fclose($new_file); 
  22.  
  23.  return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file 
  24.  
  25.  }else{ 
  26.  
  27.  //use stored file 
  28.  
  29.  return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file 
  30.  
  31.  } 
  32.  
  33. } 

并且,用法是这样的:

  1. $files = array( 
  2.  
  3.  'http://example/files/sample_js_file_1.js', 
  4.  
  5.  'http://example/files/sample_js_file_2.js', 
  6.  
  7.  'http://example/files/beautyquote_functions.js', 
  8.  
  9.  'http://example/files/crop.js', 
  10.  
  11.  'http://example/files/jquery.autosize.min.js', 
  12.  
  13.  ); 
  14.  
  15. echo combine_my_files($files, 'minified_files/', md5("my_mini_file").".js"); 

3.查看你的电子邮件是否已读

当发送电子邮件时,你会希望知道你的邮件是否已读。这里有一个非常有趣的代码片段,它可以记录阅读你邮件的IP地址,以及实际的日期和时间。

  1. <? 
  2.  
  3. error_reporting(0); 
  4.  
  5. Header("Content-Type: image/jpeg"); 
  6.  
  7. //Get IP 
  8.  
  9. if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) 
  10.  
  11. { 
  12.  
  13.  $ip=$_SERVER['HTTP_CLIENT_IP']; 
  14.  
  15. } 
  16.  
  17. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
  18.  
  19. { 
  20.  
  21.  $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
  22.  
  23. } 
  24.  
  25. else 
  26.  
  27. { 
  28.  
  29.  $ip=$_SERVER['REMOTE_ADDR']; 
  30.  
  31. } 
  32.  
  33. //Time 
  34.  
  35. $actual_time = time(); 
  36.  
  37. $actual_day = date('Y.m.d', $actual_time); 
  38.  
  39. $actual_day_chart = date('d/m/y', $actual_time); 
  40.  
  41. $actual_hour = date('H:i:s', $actual_time); 
  42.  
  43. //GET Browser 
  44.  
  45. $browser = $_SERVER['HTTP_USER_AGENT']; 
  46.  
  47. //LOG 
  48.  
  49. $myFile = "log.txt"; 
  50.  
  51. $fh = fopen($myFile, 'a+'); 
  52.  
  53. $stringData = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "/r/n"; 
  54.  
  55. fwrite($fh, $stringData); 
  56.  
  57. fclose($fh); 
  58.  
  59. //Generate Image (Es. dimesion is 1x1) 
  60.  
  61. $newimage = ImageCreate(1,1); 
  62.  
  63. $grigio = ImageColorAllocate($newimage,255,255,255); 
  64.  
  65. ImageJPEG($newimage); 
  66.  
  67. ImageDestroy($newimage); 
  68.  
  69. ?> 

4.从网页提取关键词

正如这小标题所说的那样:这个代码片段能让你轻易地从网页中提取元关键词。

  1. $meta = get_meta_tags('http://www.emoticode.net/'); 
  2.  
  3. $keywords = $meta['keywords']; 
  4.  
  5. // Split keywords 
  6.  
  7. $keywords = explode(',', $keywords ); 
  8.  
  9. // Trim them 
  10.  
  11. $keywords = array_map( 'trim', $keywords ); 
  12.  
  13. // Remove empty values 
  14.  
  15. $keywords = array_filter( $keywords ); 
  16.  
  17. print_r( $keywords ); 

5.查找页面上的所有链接

使用DOM,你可以轻松地抓取来网页上的所有链接。这里有一个工作示例:

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

6.自动转换URL为可点击的超链接

在WordPress中,如果你想在字符串中自动转换所有的URL成可点击的超链接,那么使用内置函数make_clickable()可以让你心想事成。如果你需要在WordPress之外这么做,那么你可以在wp-includes/formatting.php参考该函数的源代码:

  1. function _make_url_clickable_cb($matches) { 
  2.  
  3. $ret = ''; 
  4.  
  5. $url = $matches[2]; 
  6.  
  7. if ( emptyempty($url) ) 
  8.  
  9. return $matches[0]; 
  10.  
  11. // removed trailing [.,;:] from URL 
  12.  
  13. if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) { 
  14.  
  15. $ret = substr($url, -1); 
  16.  
  17. $url = substr($url, 0, strlen($url)-1); 
  18.  
  19. } 
  20.  
  21. return $matches[1] . "<a href="/"$url/"" rel="/"nofollow/"">$url</a>" . $ret; 
  22.  
  23. } 
  24.  
  25. function _make_web_ftp_clickable_cb($matches) { 
  26.  
  27. $ret = ''; 
  28.  
  29. $dest = $matches[2]; 
  30.  
  31. $dest = 'http://' . $dest; 
  32.  
  33. if ( emptyempty($dest) ) 
  34.  
  35. return $matches[0]; 
  36.  
  37. // removed trailing [,;:] from URL 
  38.  
  39. if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) { 
  40.  
  41. $ret = substr($dest, -1); 
  42.  
  43. $dest = substr($dest, 0, strlen($dest)-1); 
  44.  
  45. } 
  46.  
  47. return $matches[1] . "<a href="/"$dest/"" rel="/"nofollow/"">$dest</a>" . $ret; 
  48.  
  49. } 
  50.  
  51. function _make_email_clickable_cb($matches) { 
  52.  
  53. $email = $matches[2] . '@' . $matches[3]; 
  54.  
  55. return $matches[1] . "<a href="/"mailto:$email/"">$email</a>"; 
  56.  
  57. } 
  58.  
  59. function make_clickable($ret) { 
  60.  
  61. $ret = ' ' . $ret; 
  62.  
  63. // in testing, using arrays here was found to be faster 
  64.  
  65. $ret = preg_replace_callback('#([/s>])([/w]+?://[/w//x80-//xff/#$%&~/./-;:=,?@/[/]+]*)#is', '_make_url_clickable_cb', $ret); 
  66.  
  67. $ret = preg_replace_callback('#([/s>])((www|ftp)/.[/w//x80-//xff/#$%&~/./-;:=,?@/[/]+]*)#is', '_make_web_ftp_clickable_cb', $ret); 
  68.  
  69. $ret = preg_replace_callback('#([/s>])([.0-9a-z_+-]+)@(([0-9a-z-]+/.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret); 
  70.  
  71. // this one is not in an array because we need it to run last, for cleanup of accidental links within links 
  72.  
  73. $ret = preg_replace("#(<a( [^="">]+?>|>))<a [^="">]+?>([^>]+?)</a>#i", "$1$3", $ret); 
  74.  
  75. $ret = trim($ret); 
  76.  
  77. return $ret; 
  78.  
  79. } 
  80.  
  81. </a(> 

7.在你的服务器上下载并保存远程图像

在远程服务器上下载一个图像,并将其保存在自己的服务器上,在建立网站时很有用,而且这也很容易做到。下面的这两行代码就能为你办到。

$image = file_get_contents('http://www.url.com/image.jpg');

file_put_contents('/images/image.jpg', $image); //Where to save the image

8.检测浏览器语言

如果你的网站使用多种语言,那么检测浏览器语言,并将这种语言作为默认语言会很有用。下面的代码将返回客户浏览器使用的语言。

  1. function get_client_language($availableLanguages, $default='en'){ 
  2.  
  3. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { 
  4.  
  5. $langs=explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']); 
  6.  
  7. foreach ($langs as $value){ 
  8.  
  9. $choice=substr($value,0,2); 
  10.  
  11. if(in_array($choice, $availableLanguages)){ 
  12.  
  13. return $choice; 
  14.  
  15. } 
  16.  
  17. } 
  18.  
  19. }  
  20.  
  21. return $default; 
  22.  
  23. } 

9.全文显示Facebook粉丝的数量

如果你的网站或博客有一个Facebook的页面,那么你可能想要显示你有多少个粉丝。这个代码片段可以帮助你获取Facebook粉丝的数量。不要忘记在第二行添加你的页面ID。页面ID可以在地址http://facebook.com/yourpagename/info找到。

  1. <?php 
  2.  
  3. $page_id = "302807633129400"; 
  4.  
  5. $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"); 
  6.  
  7. $fans = $xml->page->fan_count; 
  8.  
  9. echo $fans; 
  10.  
  11. ?> 

以上就是本文的全部内容,希望对大家的学习有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表