为开发者准备的9个实用PHP代码片段(转)

[导读] 当你开发网站、app或博客系统时,如果有一些实用的代码片段可以直接使用,就可以节省你大量的时间和精力。这篇文章就为你分享几个实用的PHP代码片段,帮助你的Web开发。

       本文由PHP100中文网编译,转载请看文末的转载要求,谢谢合作!
当你开发网站、app或博客系统时,如果有一些实用的代码片段可以直接使用,就可以节省你大量的时间和精力。这篇文章就为你分享几个实用的PHP代码片段,帮助你的Web开发。更多PHP的学习内容,您还可以参考《深入探讨PHP类的封装与继承》《PHP比较运算符的详细学习》《国外PHP学习网站书籍资料汇总》《超实用PHP函数总结整理》,希望对你的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);

?>

源代码:http://www.emoticode.net/php/code-to-find-out-if-your-email-has-been-read.html

 

二.从网页中提取关键词

这段优秀的代码可以简单地实现从网页中提取关键词的功能。

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

源代码:http://www.emoticode.net/php/extract-keywords-from-any-webpage.html

 

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

使用DOM,你可以在任意页面上抓取链接,示例如下。

$html = file_get_contents('http://www.php100.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.'';
}

源代码:http://snipplr.com/view/70489/find-all-links-on-a-page/

 

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

在Wordpress中,如果你想自动转换所有的URLs为可点击超链接,你就可以使用内置函数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] . "$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] . "$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;
}

源代码:http://zenverse.net/php-function-to-auto-convert-url-into-hyperlink/
 

 

五.创建数据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";
}

源代码:http://css-tricks.com/snippets/php/create-data-uris/

 

六.下载和保存远程图片到你的服务器

当你在搭建网站时,很可能会从远程服务器上下载图片保存到你自己的服务器上,下面的代码就可以帮助你实现这个功能。

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

源代码:http://www.catswhocode.com/blog/snippets/download-save-a-remote-image-on-your-server-using-php

 

七.移除Microsoft Word HTML标签

当你使用Microsoft Word时,会创建很多标签tag,比如font、span、style、class等,这些标签在Word中十分有用,但 当你从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
}

源代码:http://tim.mackey.ie/CommentView,guid,2ece42de-a334-4fd0-8f94-53c6602d5718.aspx

 

八.检测浏览器语言

如果你的网站是多种语言的,下面的代码可以帮助你检测浏览器语言,它会返回客户端浏览器的默认语言。

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

源代码:http://snipplr.com/view/12631/detect-browser-language/

 

九.显示Facebook上的粉丝数量

如果在你的网站或博客中,链有Facebook页面,你可能希望显示Facebook上的粉丝数量,下面的代码就可以帮助你获取粉丝数量,另外不要忘记在代码第二行添加你的页面ID。

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

源代码:http://www.wprecipes.com/display-number-of-facebook-fans-in-full-text-on-your-wordpress-blog







原文:http://www.catswhocode.com/blog/useful-snippets-for-php-developers
译文:http://www.php100.com/html/dujia/2015/0108/8305.html
(翻译:PHP100_Zeroing) 
 

转载于:https://www.cnblogs.com/huojing/articles/4521840.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/574577.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

idea 自动生产序列吗,IDEA自动生成序列化Id

实体对象实现了java.io.Serializable接口后&#xff0c;一般都会提供一个serialVersionUID以做版本区分。在idea里&#xff0c;可以通过设置来快速生成serialVersionUID。设置方法1、打开Preferences–>Editor–>Inspections&#xff0c;然后在右侧输入UID进行搜索(搜索方…

ZH奶酪:Ionic中(弹出式窗口)的$ionicModal使用方法

Ionic中[弹出式窗口]有两种&#xff08;如下图所示&#xff09;&#xff0c;$ionicModal和$ionicPopup; $ionicModal是完整的页面&#xff1b; $ionicPopup是(Dialog)对话框样式的&#xff0c;直接用JavaScript设定对话框的一些参数&#xff0c;通常用于通知消息、确认等作用&a…

php getdefaultvalue,PHP ReflectionParameter getDefaultValueConstantName()用法及代码示例

ReflectionParameter::getDefaultValueConstantName()函数是PHP中的内置函数&#xff0c;如果默认值为常数或null&#xff0c;则用于返回默认值的常数名称。用法:string ReflectionParameter::getDefaultValueConstantName ( void )参数&#xff1a;该函数不接受任何参数。返回…

php表单中姓名必须使用汉字,我想在表单验证中加入中文姓名合法性模糊匹配判断?...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼刚开始只是想检验一下输入的是不是中文&#xff0c;后来学了正则表达式后&#xff0c;想尝试一下&#xff0c;把常见的姓氏通过字符串判断的形式&#xff0c;主要是对姓氏进行验证&#xff0c;当然还有输入长度&#xff0c;可我对自…

php实现购物车 redis,redis 哈希数据类型简单操作(实现购物车案例)

这里不累赘如何安装redis和php redis扩展&#xff0c;主要熟悉调用redis哈希数据类型如图简单方法操作如下1&#xff1a;hSet2:hGet4:hDel5:hGetAll4:hExists5:hIncrBy简单购物车实现namespaceHome\Controller;useThink\Controller;useOrg\Net\Http;useThink\Cache\Driver\Red…

写在25岁

虽然到25岁&#xff0c;大家会告诉你女人容颜开始衰退&#xff0c;要多加注意保养&#xff0c;要学会化妆&#xff0c;要会穿高跟鞋。虽然到25岁&#xff0c;大家告诉你要赶紧结婚生子&#xff0c;否则女人开始贬值。虽然到25岁&#xff0c;大家会告诉你工作不要那么拼&#xf…

matlab中D A1在哪,A1=d(1:15,:);A2=d(16:30,:);A3=

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼A1d(1:15,:);A2d(16:30,:);A3d(31:45,:);A4d(46:60,:);A5d(61:75,:);A6d(76:90,:);B1d(91:105,:);B2d(106:120,:);B3d(121:135,:);B4d(136:150,:);B5d(151:165,:);B6d(166:180,:);B7d(181:195,:);B8d(196:210,:);B9d(211:225,:);C1…

使用block的好处

1 使用block 可以轻松地绑定各处代码块&#xff0c;使用delete 结构是分散的&#xff0c;不利于变量之间传值&#xff0c;不像block可以随意地获取变量值。 2.使用block可以方便执行异步代码&#xff0c;作为异步处理回调。 In terms of code readability, the block makes it …

python mysql ssl,python – 在SQLAlchemy中使用SSL

我最近改变了我的项目使用SQLAlchemy并且我的项目运行正常,它使用了外部MySQL服务器.现在我正在尝试使用具有SSL CA的不同MySQL服务器,并且它不会连接.(它确实使用MySQL Workbench进行连接,因此证书应该没问题)我正在使用以下代码&#xff1a;ssl_args {ssl: {ca: ca_path}}en…

Easyui中使用jquery或js动态添加元素时出现的样式失效的解决方法

Easyui中使用jquery或js动态添加元素时出现的样式失效的解决方法 在添加完之后&#xff0c;可以使用 $.parser.parse();这个方法进行处理:(1) 对整个页面重新渲染: $.parser.parse();  (2) 渲染某个特定的组件:var targetObj $("<input namemydate classeasyui-date…

ftp完成版本更新php,php – 将开发团队从FTP转换为版本控制系统

问题&#xff1a;>你(他们)从来没有遇到过灾难,你(他们)需要恢复到以前版本的网站,但却不能因为他们破坏了它&#xff1f;>他们是否使用临时Web服务器来测试更改&#xff1f;>当然,如果没有某些测试,他们不会修改生产服务器中的代码&#xff1f;我怀疑第一个的答案是“…

IOS-NSDateFormatter使用介绍

IOS-NSDateFormatter使用介绍 NSDateFormatter的使用&#xff1a; NSDate *nowDate [[NSDate alloc] init];NSDateFormatter *dateFormatter [[NSDateFormatter alloc] init];[dateFormatter setDateFormat:"yyyy-mm"];NSString *time [dateFormatter stringFromD…

php scsi平台,三大SCSI Target平台PK:让服务器化身SAN

就服务器而言&#xff0c;从虚拟化平台到数据库应用的许多功能&#xff0c;都需要有SAN存储设备的支持&#xff0c;但是对于模拟测试、教学之类的应用来说&#xff0c;受到成本限制采购SAN存储设备便有所困难。特别是企业&#xff0c;都不会仅仅为了测试等常态使用的用途&#…

[BZOJ 1012] [JSOI 2008] 最大数maxnumber

1012: [JSOI2008]最大数maxnumber Time Limit: 3 Sec Memory Limit: 162 MBSubmit: 5094 Solved: 2276[Submit][Status][Discuss]Description 现在请求你维护一个数列&#xff0c;要求提供以下两种操作&#xff1a; 1、 查询操作。语法&#xff1a;Q L 功能&#xff1a;查询当…

php 数组元素往后移动,php 二维数组 元素移动

[已关闭问题]关闭于 2014-11-20 16:02二维数组元素如何实现&#xff0c;满足一定的条件&#xff0c;跳到下下个元素&#xff0c;不满足的话&#xff0c;顺序执行呢&#xff1f;比如&#xff1a;header("Content-type:text/html;charsetutf-8");$arr array(array(id&…

RequireJS

RequireJS 2.0 正式发布 RequireJS入门&#xff08;一&#xff09; RequireJS入门&#xff08;二&#xff09; RequireJS入门&#xff08;三&#xff09; RequireJS进阶&#xff08;一&#xff09; RequireJS进阶&#xff08;二&#xff09; RequireJS进阶&#xff08;三&…

帝国cms仿php自媒体新闻系统,帝国CMS仿《砍柴网》源码 专栏自媒体投稿资讯文章新闻网站模板...

在开发妹入手了一套模版&#xff0c;测试效果真心不错这里发出来供大家参考研究源码简介一家拥有全球视野的前沿科技媒体&#xff0c;我们始终秉承观点独到、全面深入、有料有趣的宗旨&#xff0c;在科技与人文之间寻找商业新价值&#xff0c;坚持以人文的视角解读科技&#xf…

【Win10】UAP/UWP/通用 开发之 x:Bind

【Win10】UAP/UWP/通用 开发之 x:Bind [Some information relates to pre-released product which may be substantially modified before its commercially released. Microsoft makes no warranties, express or implied, with respect to the information provided here.] […

root 授予oracle权限,oracle – 列出具有root(管理)权限的用户

以下是您查找用户权限的方法&#xff1a;selectlpad( , 2*level) || granted_role "User, his roles and privileges"from(/* THE USERS */selectnull grantee,username granted_rolefromdba_users/* THE ROLES TO ROLES RELATIONS */unionselectgrantee,granted_rol…

(转)基于libRTMP的流媒体直播之 AAC、H264 推送

参考&#xff1a; 1&#xff0c;基于libRTMP的流媒体直播之 AAC、H264 推送 http://billhoo.blog.51cto.com/2337751/1557646转载于:https://www.cnblogs.com/tangxiacun/p/4536904.html