9个经典的PHP代码片段分享


Posted in PHP onDecember 18, 2014

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

当你在发送邮件时,你或许很想知道该邮件是否被对方已阅读。这里有段非常有趣的代码片段能够显示对方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.'<br />';

}

四、自动转换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;

}

五、创建数据URL

数据URL可以直接嵌入到HTML/CSS/JS中,以节省大量的 HTTP请求。 下面的这段代码可利用$file轻松创建数据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会创建许多Tag,比如font,span,style,class等。这些标签对于Word本身而言是非常有用的,但是当你从Word粘贴至网页时,你会发现很多无用的Tag。因此,下面的这段代码可帮助你删除所有无用的Word HTML Tag。

function cleanHTML($html) {

/// <summary>

/// Removes all FONT and SPAN tags, and all Class and Style attributes.

/// Designed to get rid of non-standard Microsoft Word HTML tags.

/// </summary>

// 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

}

[code]
八、检测浏览器语言

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

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页面,你或许想知道拥有多少粉丝。这段代码将帮助你查看Facebook粉丝数,记住,别忘了在你的页面ID第二行添加该段代码。

<?php

    $page_id = "YOUR PAGE-ID";

    $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;

?>

以上9个超级实用经典的PHP代码非常的好用,小伙伴们参考下自由发挥,稍作修改就可以用到自己的项目中了。

PHP 相关文章推荐
php入门小知识
Mar 24 PHP
php cookies中删除的一般赋值方法
May 07 PHP
Linux下CoreSeek及PHP扩展模块的安装
Sep 23 PHP
php获取目录所有文件并将结果保存到数组(实例)
Oct 25 PHP
PHP防止注入攻击实例分析
Nov 03 PHP
php网站被挂木马后的修复方法总结
Nov 06 PHP
PHP向浏览器输出内容的4个函数总结
Nov 17 PHP
一张表搞清楚php is_null、empty、isset的区别
Jul 07 PHP
php实现基于openssl的加密解密方法
Sep 30 PHP
PHP使用XMLWriter读写xml文件操作详解
Jul 31 PHP
laravel 解决后端无法获取到前端Post过来的值问题
Oct 22 PHP
在 Laravel 6 中缓存数据库查询结果的方法
Dec 11 PHP
PHP程序员必须清楚的问题汇总
Dec 18 #PHP
8个PHP程序员常用的功能汇总
Dec 18 #PHP
ThinkPHP打开验证码页面显示乱码的解决方法
Dec 18 #PHP
ThinkPHP中使用ajax接收json数据的方法
Dec 18 #PHP
2014最热门的24个php类库汇总
Dec 18 #PHP
ThinkPHP通过AJAX返回JSON的两种实现方法
Dec 18 #PHP
ThinkPHP内置jsonRPC的缺陷分析
Dec 18 #PHP
You might like
PHP字符串中特殊符号的过滤方法介绍
2014/02/18 PHP
ThinkPHP写数组插入与获取最新插入数据ID实例
2014/11/03 PHP
PHP批量查询WordPress留言者E-mail地址实现方法
2015/02/15 PHP
PHP新建类问题分析及解决思路
2015/11/19 PHP
从父页面读取和操作iframe中内容方法
2009/07/25 Javascript
js弹出层永远居中实现思路及代码
2013/11/29 Javascript
js中回调函数的学习笔记
2014/07/31 Javascript
javascript中setAttribute()函数使用方法及兼容性
2015/07/19 Javascript
node.js微信公众平台开发教程
2016/03/04 Javascript
AngularJS控制器之间的数据共享及通信详解
2016/08/01 Javascript
bootstrap侧边栏圆点导航
2017/01/11 Javascript
树结构之JavaScript
2017/01/24 Javascript
vue基于Element构建自定义树的示例代码
2017/09/19 Javascript
vue移动UI框架滑动加载数据的方法
2018/03/12 Javascript
JS实现数组去重及数组内对象去重功能示例
2019/02/02 Javascript
vue 引用自定义ttf、otf、在线字体的方法
2019/05/09 Javascript
8个有意思的JavaScript面试题
2019/07/30 Javascript
vue-loader中引入模板预处理器的实现
2019/09/04 Javascript
JavaScript经典案例之简易计算器
2020/08/24 Javascript
Vue实现省市区三级联动
2020/12/27 Vue.js
[04:28]2014DOTA2国际邀请赛 采访小兔子LGD挺进钥匙体育馆
2014/07/14 DOTA
[03:40]DOTA2亚洲邀请赛小组赛第二日 赛事回顾
2015/01/31 DOTA
[03:33]TI9战队采访 - Infamous
2019/08/20 DOTA
pycharm 使用心得(八)如何调用另一文件中的函数
2014/06/06 Python
python win32 简单操作方法
2017/05/25 Python
深入浅出学习python装饰器
2017/09/29 Python
python线程join方法原理解析
2020/02/11 Python
pytorch查看通道数 维数 尺寸大小方式
2020/05/26 Python
CSS3为背景图设置遮罩并解决遮罩样式继承问题
2020/06/22 HTML / CSS
幼儿园保教管理制度
2014/02/03 职场文书
人事专员职责
2014/02/22 职场文书
2014社区三八妇女节活动方案
2014/03/30 职场文书
南京市纪委监察局整改方案
2014/09/16 职场文书
大学生读书笔记范文
2015/07/01 职场文书
酒店宣传语大全
2015/07/13 职场文书
HTML5来实现本地文件读取和写入的实现方法
2021/05/25 HTML / CSS