9个PHP实用功能代码片段推荐
一、查看邮件是否已被阅读
在发送邮件后,了解对方是否已阅读是常见需求。以下代码片段可记录访问者的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); ?>
二、从网页中提取关键字
借助一段简洁的代码,可以轻松从指定网页中抓取并处理元数据中的关键字。
复制代码 代码如下: $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 );
三、查找页面上的所有链接
利用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.' '; }
四、自动转换URL,跳转至超链接
在WordPress环境中,可使用内置函数make_clickable()自动将文本中的URL转换为可点击的超链接。若需在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] . "$url" . $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] . "$dest" . $ret; } function _make_email_clickable_cb($matches) { $email = $matches[2] . '@' . $matches[3]; return $matches[1] . "$emailmailto:$email\">$email"; } 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("#(]+?>|>))]+?>([^>]+?)#i", "$1$3", $ret); $ret = trim($ret); return $ret; }
五、创建数据URL
数据URL允许将资源直接嵌入HTML、CSS或JS中,从而减少HTTP请求数量。以下代码展示了如何基于文件轻松生成数据URL。
复制代码 代码如下: function data_uri($file, $mime) { $contents=file_get_contents($file); $base64=base64_encode($contents); echo "data:$mime;base64,$base64"; }
六、从服务器上下载&保存一个远程图片
在网站搭建过程中,经常需要从远程服务器下载图片并保存到本地服务器。以下是实现该操作的代码示例。
复制代码 代码如下: $image = file_get_contents('http://www.url.com/image.jpg'); file_put_contents('/images/image.jpg', $image); //Where to save the image
七、移除Remove Microsoft Word HTML Tag
Microsoft Word生成的HTML通常包含大量如font、span、style、class等标签。这些标签对Word有用,但在网页中往往显得冗余。以下代码可帮助清除这些无用的Word HTML标签。
复制代码 代码如下: function cleanHTML($html) { /// /// Removes all FONT and SPAN tags, and all Class and Style attributes. /// Designed to get rid of non-standard Microsoft Word HTML tags. /// // start by completely removing all unwanted tags $html = ereg_replace("<(/)?(font|span|del|ins)[^>]*>","",$html); // then run another pass over the html (twice), removing unwanted attributes $html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html); $html = ereg_replace("<([^>]*)(class|lang|style|size|face)=("[^"]*"|'[^']*'|[^>]+)([^>]*)>","<\1>",$html); return $html }
八、检测浏览器语言
对于多语言网站,可以使用此代码检测浏览器客户端的默认语言设置,并返回首选的语言代码。
复制代码 代码如下: 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; }
九、显示Facebook 粉丝数量
如果网站或博客链接了Facebook页面,可能需要获取其粉丝数量。以下代码可用于查询粉丝数,使用时请记得替换代码第二行中的页面ID。
复制代码 代码如下: