21个实用便利的PHP代码(上)(整理)
1. PHP可阅读随机字符串
此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; 17 }
2. PHP生成一个随机字符串
如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; 11 }
3. PHP编码电子邮件地址
使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' ) 2 { 3 // remplazar aroba y puntos 4 $email = str_replace('@', '@', $email); 5 $email = str_replace('.', '.', $email); 6 $email = str_split($email, 5); 7 8 $linkText = str_replace('@', '@', $linkText); 9 $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 记录,使邮件验证功能更加强大。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; 13 }
5. PHP列出目录内容
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br>'."\n"; 12 } 13 } 14 closedir($handle); 15 } 16 } 17 }
6. PHP销毁目录
删除一个目录,包括它的内容。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 } 35 }
7. PHP解析 JSON 数据
与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 数据
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 //xml string 2 $xml_string="<?xml version='1.0'?> 3 <users> 4 <user id='398'> 5 <name>Foo</name> 6 <email>foo@bar.com</name> 7 </user> 8 <user id='867'> 9 <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 18 foreach ($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 />';
9. PHP创建日志缩略名
创建用户友好的日志缩略名。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 function create_slug($string){ 2 $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string); 3 return $slug; 4 }
10. PHP获取客户端真实 IP 地址
该函数将获取用户的真实 IP 地址,即便他使用代理服务器。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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; 17 }