分享经常用到的21个PHP函数代码段(上)
创始人
2024-08-02 22:31:27
0

下面介绍的是,在PHP开发中,经常用到的21个函数代码段,当我们用到的时候,就可以直接用了。

1. PHP可阅读随机字符串

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

 

  1. /**************  
  2. *@length – length of random string (must be a multiple of 2)  
  3. **************/ 
  4. function readable_random_string($length = 6){  
  5. $conso=array(“b”,”c”,”d”,”f”,”g”,”h”,”j”,”k”,”l”,  
  6. “m”,”n”,”p”,”r”,”s”,”t”,”v”,”w”,”x”,”y”,”z”);  
  7. $vocal=array(“a”,”e”,”i”,”o”,”u”);  
  8. $password=”";  
  9. 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;  

 

2. PHP生成一个随机字符串

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

 

  1. /*************  
  2. *@l – length of random string  
  3. */ 
  4. function generate_rand($l){  
  5. $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;  
  6. srand((double)microtime()*1000000);  
  7. for($i=0; $i<$l; $i++) {  
  8. $rand.= $c[rand()%strlen($c)];  
  9. }  
  10. return $rand;  

 

3. PHP编码电子邮件地址

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

 

  1. function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, 
  2. $attrs =’class=”emailencoder”‘ )  
  3. {  
  4. // remplazar aroba y puntos  
  5. $email = str_replace(‘@’, ‘@’, $email);  
  6. $email = str_replace(‘.’, ‘.’, $email);  
  7. $email = str_split($email, 5);  
  8. $linkText = str_replace(‘@’, ‘@’, $linkText);  
  9. $linkText = str_replace(‘.’, ‘.’, $linkText);  
  10. $linkText = str_split($linkText, 5);  
  11. $part1 = ‘
  12. $part2 = ‘ilto:’;  
  13. $part3 = ‘” ‘. $attrs .’ >’;  
  14. $part4 = ‘’;  
  15. $encoded = ‘’;  
  16. $encoded .= “document.write(‘$part1′);”;  
  17. $encoded .= “document.write(‘$part2′);”;  
  18. foreach($email as $e)  
  19. {  
  20. $encoded .= “document.write(‘$e’);”;  
  21. }  
  22. $encoded .= “document.write(‘$part3′);”;  
  23. foreach($linkText as $l)  
  24. {  
  25. $encoded .= “document.write(‘$l’);”;  
  26. }  
  27. $encoded .= “document.write(‘$part4′);”;  
  28. $encoded .= ‘’;  
  29. return $encoded;  

 

4. PHP验证邮件地址

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

 

  1. function is_valid_email($email, $test_mx = false)  
  2. {  
  3. if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))  
  4. if($test_mx)  
  5. {  
  6. list($username, $domain) = split(“@”, $email);  
  7. return getmxrr($domain, $mxrecords);  
  8. }  
  9. else 
  10. return true;  
  11. else 
  12. return false;  

 

5. PHP列出目录内容

 

  1. function list_files($dir)  
  2. {  
  3. if(is_dir($dir))  
  4. {  
  5. if($handle = opendir($dir))  
  6. {  
  7. while(($file = readdir($handle)) !== false)  
  8. {  
  9. if($file != “.” && $file != “..” && $file != “Thumbs.db”)  
  10. {  
  11. echo ‘’.$file.’
    ’.”\n”;  
  12. }  
  13. }  
  14. closedir($handle);  
  15. }  
  16. }  

 

#p#

6. PHP销毁目录

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

 

  1. /*****  
  2. *@dir – Directory to destroy  
  3. *@virtual[optional]- whether a virtual directory  
  4. */ 
  5. function destroyDir($dir, $virtual = false)  
  6. {  
  7. $ds = DIRECTORY_SEPARATOR;  
  8. $dir = $virtual ? realpath($dir) : $dir;  
  9. $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. }  

 

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);  
  3. echo $obj->name; //prints foo  
  4. echo $obj->interest[1]; //prints php 

 

8. PHP解析 XML 数据

 

  1. //xml string  
  2. $xml_string=”  
  3.  
  4.  
  5. Foo  
  6. foo@bar.com  
  7.  
  8.  
  9. Foobar  
  10. foobar@foo.com  
  11.  
  12. ”;  
  13. //load the xml string using simplexml  
  14. $xml = simplexml_load_string($xml_string);  
  15. //loop through the each node of user  
  16. foreach ($xml->user as $user)  
  17. {  
  18. //access attribute  
  19. echo $user['id'], ‘ ‘;  
  20. //subnodes are accessed by -> operator  
  21. echo $user->name, ‘ ‘;  
  22. echo $user->email, ‘’;  

 

9. PHP创建日志缩略名

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

 

  1. function create_slug($string){  
  2. $slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);  
  3. return $slug;  

 

10. PHP获取客户端真实 IP 地址

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

 

  1. function getRealIpAddr()  
  2. {  
  3. if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))  
  4. {  
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];  
  6. }  
  7. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))  
  8. //to check ip is pass from proxy  
  9. {  
  10. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];  
  11. }  
  12. else 
  13. {  
  14. $ip=$_SERVER['REMOTE_ADDR'];  
  15. }  
  16. return $ip;  

 

11. PHP强制性文件下载

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

 

  1. /********************  
  2. *@file – path to file  
  3. */ 
  4. function force_download($file)  
  5. {  
  6. if ((isset($file))&&(file_exists($file))) {  
  7. header(“Content-length: “.filesize($file));  
  8. header(‘Content-Type: application/octet-stream’);  
  9. header(‘Content-Disposition: attachment; filename=”‘ . $file . ‘”‘);  
  10. readfile(“$file”);  
  11. } else {  
  12. echo “No file selected”;  
  13. }  

 

经常用到的函数段,请看下一篇,

【编辑推荐】

  1. 介绍生成PHP网站页面静态化的方法
  2. php基础 关于继承的使用方法
  3. 分享PHP网站建设的流程与步骤
  4. PHP新手 学习基本语法
  5. 详细介绍Session在PHP中的使用

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
Windows恶意软件20年“... 在Windows的早期年代,病毒游走于系统之间,偶尔删除文件(但被删除的文件几乎都是可恢复的),并弹...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
着眼MAC地址,解救无法享受D... 在安装了DHCP服务器的局域网环境中,每一台工作站在上网之前,都要先从DHCP服务器那里享受到地址动...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...