PHP一些实用的自定义函数收集

虽然PHP自带的函数库很强大,但是在日常很多情况下,我们也还得自己写自定义的函数去实现某些功能与需求。下面收集了一些比较实用的、解决一些常见需求的自定义函数,比如将网址字符串转换成超级链接、列出目录内容、验证邮件地址等等,如果你觉得好,可以收藏本页,方便以后翻阅~

1. PHP可阅读随机字符串

此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。

01/**************
02*@length - length of random string (must be a multiple of 2)
03**************/
04function readable_random_string($length = 6){
05    $conso=array("b","c","d","f","g","h","j","k","l",
06    "m","n","p","r","s","t","v","w","x","y","z");
07    $vocal=array("a","e","i","o","u");
08    $password="";
09    srand ((double)microtime()*1000000);
10    $max = $length/2;
11    for($i=1; $i<=$max; $i++)
12    {
13    $password.=$conso[rand(0,19)];
14    $password.=$vocal[rand(0,4)];
15    }
16    return $password;
17}
2. PHP生成一个随机字符串

如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。

01/*************
02*@l - length of random string
03*/
04function generate_rand($l){
05  $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
06  srand((double)microtime()*1000000);
07  for($i=0; $i < $l; $i++) {
08      $rand.= $c[rand()%strlen($c)];
09  }
10  return $rand;
11}
3. PHP编码电子邮件地址

使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。

01function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
02{
03    // remplazar aroba y puntos
04    $email = str_replace('@', '@', $email);
05    $email = str_replace('.', '.', $email);
06    $email = str_split($email, 5);  
07  
08    $linkText = str_replace('@', '@', $linkText);
09    $linkText = str_replace('.', '.', $linkText);
10    $linkText = str_split($linkText, 5);  
11  
12    $part1 = '<a href="ma';
13    $part2 = 'ilto:';
14    $part3 = '" '. $attrs .' >';
15    $part4 = '</a>';  
16  
17    $encoded = '<script type="text/javascript">';
18    $encoded .= "document.write('$part1');";
19    $encoded .= "document.write('$part2');";
20    foreach($email as $e)
21    {
22            $encoded .= "document.write('$e');";
23    }
24    $encoded .= "document.write('$part3');";
25    foreach($linkText as $l)
26    {
27            $encoded .= "document.write('$l');";
28    }
29    $encoded .= "document.write('$part4');";
30    $encoded .= '</script>';  
31  
32    return $encoded;
33}
4. PHP验证邮件地址

电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。

01function is_valid_email($email, $test_mx = false)
02{
03    if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
04        if($test_mx)
05        {
06            list($username, $domain) = split("@", $email);
07            return getmxrr($domain, $mxrecords);
08        }
09        else
10            return true;
11    else
12        return false;
13}
5. PHP列出目录内容
01function list_files($dir)
02{
03    if(is_dir($dir))
04    {
05        if($handle = opendir($dir))
06        {
07            while(($file = readdir($handle)) !== false)
08            {
09                if($file != "." && $file != ".." && $file != "Thumbs.db")
10                {
11                    echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n";
12                }
13            }
14            closedir($handle);
15        }
16    }
17}
6. PHP销毁目录

删除一个目录,包括它的内容。

01/*****
02*@dir - Directory to destroy
03*@virtual[optional]- whether a virtual directory
04*/
05function destroyDir($dir, $virtual = false)
06{
07    $ds = DIRECTORY_SEPARATOR;
08    $dir = $virtual ? realpath($dir) : $dir;
09    $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
10    if (is_dir($dir) && $handle = opendir($dir))
11    {
12        while ($file = readdir($handle))
13        {
14            if ($file == '.' || $file == '..')
15            {
16                continue;
17            }
18            elseif (is_dir($dir.$ds.$file))
19            {
20                destroyDir($dir.$ds.$file);
21            }
22            else
23            {
24                unlink($dir.$ds.$file);
25            }
26        }
27        closedir($handle);
28        rmdir($dir);
29        return true;
30    }
31    else
32    {
33        return false;
34    }
35}
7. PHP解析 JSON 数据

与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。

1$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
2$obj=json_decode($json_string);
3echo $obj->name; //prints foo
4echo $obj->interest[1]; //prints php
8. PHP解析 XML 数据
01//xml string
02$xml_string="<?xml version='1.0'?>
03<users>
04<user id='398'>
05<name>Foo</name>
06<email>foo@bar.com</name>
07</user>
08<user id='867'>
09<name>Foobar</name>
10<email>foobar@foo.com</name>
11</user>
12</users>"; 
13  
14//load the xml string using simplexml
15$xml = simplexml_load_string($xml_string); 
16  
17//loop through the each node of user
18foreach ($xml->user as $user)
19{
20    //access attribute
21    echo $user['id'], ' ';
22    //subnodes are accessed by -> operator
23    echo $user->name, ' ';
24    echo $user->email, '<br />';
25}
9. PHP创建日志缩略名

创建用户友好的日志缩略名。

1function create_slug($string){
2    $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
3    return $slug;
4}
10. PHP获取客户端真实 IP 地址

该函数将获取用户的真实 IP 地址,即便他使用代理服务器。

01function getRealIpAddr()
02{
03    if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
04    {
05        $ip=$_SERVER['HTTP_CLIENT_IP'];
06    }
07    elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
08    //to check ip is pass from proxy
09    {
10        $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
11    }
12    else
13    {
14        $ip=$_SERVER['REMOTE_ADDR'];
15    }
16    return $ip;
17}
11. PHP强制性文件下载

为用户提供强制性的文件下载功能。

01/********************
02*@file - path to file
03*/
04function force_download($file)
05{
06    if ((isset($file))&&(file_exists($file))) {
07        header("Content-length: ".filesize($file));
08        header('Content-Type: application/octet-stream');
09        header('Content-Disposition: attachment; filename="' . $file . '"');
10        readfile("$file");
11    }
12    else {
13        echo "No file selected";
14    }
15}
12. PHP创建标签云
01function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
02{
03    $minimumCount = min( array_values( $data ) );
04    $maximumCount = max( array_values( $data ) );
05    $spread = $maximumCount - $minimumCount;
06    $cloudHTML = '';
07    $cloudTags = array(); 
08      
09    $spread == 0 && $spread = 1; 
10      
11    foreach( $data as $tag => $count )
12    {
13        $size = $minFontSize + ( $count - $minimumCount )
14        * ( $maxFontSize - $minFontSize ) / $spread;
15        $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px'
16        . '" href="#" title="\'' . $tag .
17        '\' returned a count of ' . $count . '">'
18        . htmlspecialchars( stripslashes( $tag ) ) . '</a>';
19    
20  
21    return join( "\n", $cloudTags ) . "\n";
22}
23/**************************
24**** Sample usage ***/
25$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,
26'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,
27'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,
28'Extract' => 28, 'Filters' => 42);
29echo getCloud($arr, 12, 36);
13. PHP寻找两个字符串的相似性

PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。

1similar_text($string1, $string2, $percent);
2//$percent will have the percentage of similarity
14. PHP在应用程序中使用 Gravatar 通用头像

随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。

01/******************
02*@email - Email address to show gravatar for
03*@size - size of gravatar
04*@default - URL of default gravatar to use
05*@rating - rating of Gravatar(G, PG, R, X)
06*/
07function show_gravatar($email, $size, $default, $rating)
08{
09    echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).
10    '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px"
11    height="'.$size.'px" />';
12}
15. PHP在字符断点处截断文字

所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。

01// Original PHP code by Chirp Internet: www.chirp.com.au
02// Please acknowledge use of this code by including this header.
03function myTruncate($string, $limit, $break=".", $pad="...") {
04    // return with no change if string is shorter than $limit
05    if(strlen($string) <= $limit)
06    return $string
07      
08    // is $break present between $limit and the end of the string?
09    if(false !== ($breakpoint = strpos($string, $break, $limit))) {
10        if($breakpoint < strlen($string) - 1) {
11            $string = substr($string, 0, $breakpoint) . $pad;
12        }
13    }
14    return $string;
15}
16/***** Example ****/
17$short_string=myTruncate($long_string, 100, ' ');
16. PHP文件 Zip 压缩
01/* creates a compressed zip file */
02function create_zip($files = array(),$destination = '',$overwrite = false) {
03    //if the zip file already exists and overwrite is false, return false
04    if(file_exists($destination) && !$overwrite) { return false; }
05    //vars
06    $valid_files = array();
07    //if files were passed in...
08    if(is_array($files)) {
09        //cycle through each file
10        foreach($files as $file) {
11        //make sure the file exists
12            if(file_exists($file)) {
13                $valid_files[] = $file;
14            }
15        }
16    }
17    //if we have good files...
18    if(count($valid_files)) {
19        //create the archive
20        $zip = new ZipArchive();
21        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
22            return false;
23        }
24        //add the files
25        foreach($valid_files as $file) {
26            $zip->addFile($file,$file);
27        }
28        //debug
29        //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status; 
30  
31        //close the zip -- done!
32        $zip->close(); 
33  
34        //check to make sure the file exists
35        return file_exists($destination);
36    }
37    else
38    {
39        return false;
40    }
41}
42/***** Example Usage ***/
43$files=array('file1.jpg', 'file2.jpg', 'file3.gif');
44create_zip($files, 'myzipfile.zip', true);
17. PHP解压缩 Zip 文件
01/**********************
02*@file - path to zip file
03*@destination - destination directory for unzipped files
04*/
05function unzip_file($file, $destination){
06    // create object
07    $zip = new ZipArchive() ;
08    // open archive
09    if ($zip->open($file) !== TRUE) {
10        die (’Could not open archive’);
11    }
12    // extract contents to destination directory
13    $zip->extractTo($destination);
14    // close archive
15    $zip->close();
16    echo 'Archive extracted to directory';
17}
18. PHP为 URL 地址预设 http 字符串

有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。

1if (!preg_match("/^(http|ftp):/", $_POST['url'])) {
2   $_POST['url'] = 'http://'.$_POST['url'];
3}
19. PHP将网址字符串转换成超级链接

该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。

01function makeClickableLinks($text) {
02    $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
03    '<a href="\1">\1</a>', $text);
04    $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
05    '\1<a href="http://\2">\2</a>', $text);
06    $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
07    '<a href="mailto:\1">\1</a>', $text); 
08      
09    return $text;
10}
20. PHP调整图像尺寸

创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。

01/**********************
02*@filename - path to the image
03*@tmpname - temporary path to thumbnail
04*@xmax - max width
05*@ymax - max height
06*/
07function resize_image($filename, $tmpname, $xmax, $ymax)
08{
09    $ext = explode(".", $filename);
10    $ext = $ext[count($ext)-1];  
11  
12    if($ext == "jpg" || $ext == "jpeg")
13        $im = imagecreatefromjpeg($tmpname);
14    elseif($ext == "png")
15        $im = imagecreatefrompng($tmpname);
16    elseif($ext == "gif")
17        $im = imagecreatefromgif($tmpname);  
18  
19    $x = imagesx($im);
20    $y = imagesy($im);  
21  
22    if($x <= $xmax && $y <= $ymax)
23        return $im;  
24  
25    if($x >= $y) {
26        $newx = $xmax;
27        $newy = $newx * $y / $x;
28    }
29    else {
30        $newy = $ymax;
31        $newx = $x / $y * $newy;
32    }  
33  
34    $im2 = imagecreatetruecolor($newx, $newy);
35    imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
36    return $im2;
37}
21. PHP检测 ajax 请求

大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。

1if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
2    //If AJAX Request Then
3}else{
4//something else
22. 关键词高亮
1function highlight($sString, $aWords) {
2    if (!is_array ($aWords) || emptyempty ($aWords) || !is_string ($sString)) {
3        return false;
4    }
5  
6    $sWords = implode ('|', $aWords);
7    return preg_replace ('@\b('.$sWords.')\b@si', '<strong style="background-color:yellow">$1</strong>', $sString);
8}
23. 获取你的Feedburner的用户
01function get_average_readers($feed_id,$interval = 7){
02    $today = date('Y-m-d', strtotime("now"));
03    $ago = date('Y-m-d', strtotime("-".$interval." days"));
04    $feed_url="https://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=".$feed_id."&dates=".$ago.",".$today;
05    $ch = curl_init();
06    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
07    curl_setopt($ch, CURLOPT_URL, $feed_url);
08    $data = curl_exec($ch);
09    curl_close($ch);
10    $xml = new SimpleXMLElement($data);
11    $fb = $xml->feed->entry['circulation'];
12  
13    $nb = 0;
14    foreach($xml->feed->children() as $circ){
15        $nb += $circ['circulation'];
16    }
17  
18    return round($nb/$interval);
19}
24. 自动生成密码
01function generatePassword($length=9, $strength=0) {
02    $vowels = 'aeuy';
03    $consonants = 'bdghjmnpqrstvz';
04    if ($strength >= 1) {
05        $consonants .= 'BDGHJLMNPQRSTVWXZ';
06    }
07    if ($strength >= 2) {
08        $vowels .= "AEUY";
09    }
10    if ($strength >= 4) {
11        $consonants .= '23456789';
12    }
13    if ($strength >= 8 ) {
14        $vowels .= '@#$%';
15    }
16  
17    $password = '';
18    $alt = time() % 2;
19    for ($i = 0; $i < $length; $i++) {
20        if ($alt == 1) {
21            $password .= $consonants[(rand() % strlen($consonants))];
22            $alt = 0;
23        } else {
24            $password .= $vowels[(rand() % strlen($vowels))];
25            $alt = 1;
26        }
27    }
28    return $password;
29}
25. 压缩多个CSS文件
01header('Content-type: text/css');
02ob_start("compress");
03function compress($buffer) {
04  /* remove comments */
05  $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
06  /* remove tabs, spaces, newlines, etc. */
07  $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
08  return $buffer;
09}
10  
11/* your css files */
12include('master.css');
13include('typography.css');
14include('grid.css');
15include('print.css');
16include('handheld.css');
17  
18ob_end_flush();
26. 获取短网址
1function getTinyUrl($url) {
2    return file_get_contents("http://tinyurl.com/api-create.php?url=".$url);
3}
27. 根据生日计算年龄
01function age($date){
02    $year_diff = '';
03    $time = strtotime($date);
04    if(FALSE === $time){
05        return '';
06    }
07  
08    $date = date('Y-m-d', $time);
09    list($year,$month,$day) = explode("-",$date);
10    $year_diff = date("Y") – $year;
11    $month_diff = date("m") – $month;
12    $day_diff = date("d") – $day;
13    if ($day_diff < 0 || $month_diff < 0) $year_diff–;
14  
15    return $year_diff;
16}
28. 计算执行时间
01//Create a variable for start time
02$time_start = microtime(true);
03  
04// Place your PHP/HTML/JavaScript/CSS/Etc. Here
05  
06//Create a variable for end time
07$time_end = microtime(true);
08//Subtract the two times to get seconds
09$time = $time_end - $time_start;
10  
11echo 'Script took '.$time.' seconds to execute';
29. PHP的维护模式
01function maintenance($mode = FALSE){
02    if($mode){
03        if(basename($_SERVER['SCRIPT_FILENAME']) != 'maintenance.php'){
04            header("Location: http://example.com/maintenance.php");
05            exit;
06        }
07    }else{
08        if(basename($_SERVER['SCRIPT_FILENAME']) == 'maintenance.php'){
09            header("Location: http://example.com/");
10            exit;
11        }
12    }
13}
30. 阻止CSS样式被缓存
1<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css" /&glt;
31. 为数字增加 st\nd\rd 等
01function make_ranked($rank) {
02    $last = substr( $rank, -1 );
03    $seclast = substr( $rank, -2, -1 );
04    if( $last > 3 || $last == 0 ) $ext = 'th';
05    else if( $last == 3 ) $ext = 'rd';
06    else if( $last == 2 ) $ext = 'nd';
07    else $ext = 'st'
08  
09    if( $last == 1 && $seclast == 1) $ext = 'th';
10    if( $last == 2 && $seclast == 1) $ext = 'th';
11    if( $last == 3 && $seclast == 1) $ext = 'th'
12  
13    return $rank.$ext;
14}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值