当前位置: 移动技术网 > IT编程>开发语言>PHP > 非常有用的9个PHP代码片段

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

2017年12月12日  | 移动技术网IT编程  | 我要评论

本文我们就来分享一下我收集的一些超级有用的php代码片段。一起来看一看吧!
1.创建数据uri

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

function data_uri($file, $mime) {
 $contents=file_get_contents($file);
 $base64=base64_encode($contents);
 echo "data:$mime;base64,$base64";
}

2.合并javascript和css文件

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

function combine_my_files($array_files, $destination_dir, $dest_file_name){
 if(!is_file($destination_dir . $dest_file_name)){ //continue only if file doesn't exist
 $content = "";
 foreach ($array_files as $file){ //loop through array list
 $content .= file_get_contents($file); //read each file
 }
 //you can use some sort of minifier here
 //minify_my_js($content);
 $new_file = fopen($destination_dir . $dest_file_name, "w" ); //open file for writing
 fwrite($new_file , $content); //write to destination
 fclose($new_file);
 return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combined file
 }else{
 //use stored file
 return '<script src="'. $destination_dir . $dest_file_name.'"></script>'; //output combine file
 }
}

并且,用法是这样的:

$files = array(
 'http://example/files/sample_js_file_1.js',
 'http://example/files/sample_js_file_2.js',
 'http://example/files/beautyquote_functions.js',
 'http://example/files/crop.js',
 'http://example/files/jquery.autosize.min.js',
 );
echo combine_my_files($files, 'minified_files/', md5("my_mini_file").".js");

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

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

<?
error_reporting(0);
header("content-type: image/jpeg");
//get ip
if (!empty($_server['http_client_ip']))
{
 $ip=$_server['http_client_ip'];
}
elseif (!empty($_server['http_x_forwarded_for']))
{
 $ip=$_server['http_x_forwarded_for'];
}
else
{
 $ip=$_server['remote_addr'];
}
//time
$actual_time = time();
$actual_day = date('y.m.d', $actual_time);
$actual_day_chart = date('d/m/y', $actual_time);
$actual_hour = date('h:i:s', $actual_time);
//get browser
$browser = $_server['http_user_agent'];
//log
$myfile = "log.txt";
$fh = fopen($myfile, 'a+');
$stringdata = $actual_day . ' ' . $actual_hour . ' ' . $ip . ' ' . $browser . ' ' . "\r\n";
fwrite($fh, $stringdata);
fclose($fh);
//generate image (es. dimesion is 1x1)
$newimage = imagecreate(1,1);
$grigio = imagecolorallocate($newimage,255,255,255);
imagejpeg($newimage);
imagedestroy($newimage);
?>

4.从网页提取关键词

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

$meta = get_meta_tags('http://www.emoticode.net/');
$keywords = $meta['keywords'];
// split keywords
$keywords = explode(',', $keywords );
// trim them
$keywords = array_map( 'trim', $keywords );
// remove empty values
$keywords = array_filter( $keywords );
print_r( $keywords );

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

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

$html = file_get_contents('http://www.example.com');
$dom = new domdocument();
@$dom->loadhtml($html);
// grab all the on the page
$xpath = new domxpath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
for ($i = 0; $i < $hrefs->length; $i++) {
 $href = $hrefs->item($i);
 $url = $href->getattribute('href');
 echo $url.'<br />';
}

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

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

function _make_url_clickable_cb($matches) {
$ret = '';
$url = $matches[2];
if ( empty($url) )
return $matches[0];
// removed trailing [.,;:] from url
if ( in_array(substr($url, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($url, -1);
$url = substr($url, 0, strlen($url)-1);
}
return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $ret;
}
function _make_web_ftp_clickable_cb($matches) {
$ret = '';
$dest = $matches[2];
$dest = 'http://' . $dest;
if ( empty($dest) )
return $matches[0];
// removed trailing [,;:] from url
if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
$ret = substr($dest, -1);
$dest = substr($dest, 0, strlen($dest)-1);
}
return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
}
function _make_email_clickable_cb($matches) {
$email = $matches[2] . '@' . $matches[3];
return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
}
function make_clickable($ret) {
$ret = ' ' . $ret;
// in testing, using arrays here was found to be faster
$ret = preg_replace_callback('#([\s>])([\w]+?://[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_url_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
$ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
// this one is not in an array because we need it to run last, for cleanup of accidental links within links
$ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
$ret = trim($ret);
return $ret;
}

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

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

$image = file_get_contents('http://www.url.com/image.jpg');
file_put_contents('/images/image.jpg', $image); //where to save the image

8.检测浏览器语言

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

function get_client_language($availablelanguages, $default='en'){
if (isset($_server['http_accept_language'])) {
$langs=explode(',',$_server['http_accept_language']);
foreach ($langs as $value){
$choice=substr($value,0,2);
if(in_array($choice, $availablelanguages)){
return $choice;
}
}
} 
return $default;
}

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

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

<?php
$page_id = "302807633129400";
$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");
$fans = $xml->page->fan_count;
echo $fans;
?>

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网