网站建设

PC + 手机 + 微信网站 + 小程序 + APP,五端合一

当前位置:首页>新闻资讯>网站建设

[北京网站制作]PHP二十一段救命代码

时间:2024-03-01   访问量:1109

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. $password.=$conso[rand(0,19)]; 
  13. $password.=$vocal[rand(0,4)]; 
  14. 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. return $rand; 

3. PHP编码电子邮件地址

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

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

4. PHP验证邮件地址

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

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

5. PHP列出目录内容

  1. function list_files($dir) 
  2. if(is_dir($dir)) 
  3. if($handle = opendir($dir)) 
  4. while(($file = readdir($handle)) !== false) 
  5. if($file != "." && $file != ".." && $file != "Thumbs.db") 
  6. echo ''.$file.'
    '."n"; 
  7. closedir($handle); 

6. PHP销毁目录

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

  1. /***** 
  2. *@dir - Directory to destroy 
  3. *@virtual[optional]- whether a virtual directory 
  4. */ 
  5. function destroyDir($dir, $virtual = false) 
  6. $ds = DIRECTORY_SEPARATOR; 
  7. $dir = $virtual ? realpath($dir) : $dir; 
  8. $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir; 
  9. if (is_dir($dir) && $handle = opendir($dir)) 
  10. while ($file = readdir($handle)) 
  11. if ($file == '.' || $file == '..') 
  12. continue; 
  13. elseif (is_dir($dir.$ds.$file)) 
  14. destroyDir($dir.$ds.$file); 
  15. else 
  16. unlink($dir.$ds.$file); 
  17. closedir($handle); 
  18. rmdir($dir); 
  19. return true; 
  20. else 
  21. return false; 

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. //access attribute 
  18. echo $user['id'], ' '; 
  19. //subnodes are accessed by -> operator 
  20. echo $user->name, ' '; 
  21. 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. if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) 
  3. $ip=$_SERVER['HTTP_CLIENT_IP']; 
  4. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
  5. //to check ip is pass from proxy 
  6. $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
  7. else 
  8. $ip=$_SERVER['REMOTE_ADDR']; 
  9. return $ip; 

11. PHP强制性文件下载

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

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

12. PHP创建标签云

  1. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 ) 
  2. $minimumCount = min( array_values( $data ) ); 
  3. $maximumCount = max( array_values( $data ) ); 
  4. $spread = $maximumCount - $minimumCount; 
  5. $cloudHTML = ''; 
  6. $cloudTags = array();  
  7. $spread == 0 && $spread = 1;  
  8. foreach( $data as $tag => $count ) 
  9. $size = $minFontSize + ( $count - $minimumCount ) 
  10. * ( $maxFontSize - $minFontSize ) / $spread; 
  11. $cloudTags[] = '
  12. . '" href="#" title="'' . $tag . 
  13. '' returned a count of ' . $count . '">' 
  14. . htmlspecialchars( stripslashes( $tag ) ) . ''; 
  15. }  
  16. return join( "n", $cloudTags ) . "n"; 
  17. /************************** 
  18. **** Sample usage ***/ 
  19. $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 
  20. 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 
  21. 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 
  22. 'Extract' => 28, 'Filters' => 42); 
  23. echo getCloud($arr, 12, 36); 

13. PHP寻找两个字符串的相似性

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

  1. similar_text($string1, $string2, $percent); 
  2. //$percent will have the percentage of similarity 

14. PHP在应用程序中使用 Gravatar 通用头像

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

  1. /****************** 
  2. *@email - Email address to show gravatar for 
  3. *@size - size of gravatar 
  4. *@default - URL of default gravatar to use 
  5. *@rating - rating of Gravatar(G, PG, R, X) 
  6. */ 
  7. function show_gravatar($email, $size, $default, $rating) 
  8. echo '
  9. height="'.$size.'px" />'; 

15. PHP在字符断点处截断文字

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

  1. // Original PHP code by Chirp Internet: www.chirp.com.au 
  2. // Please acknowledge use of this code by including this header. 
  3. function myTruncate($string, $limit, $break=".", $pad="...") { 
  4. // return with no change if string is shorter than $limit 
  5. if(strlen($string) <= $limit) 
  6. return $string;  
  7. // is $break present between $limit and the end of the string? 
  8. if(false !== ($breakpoint = strpos($string, $break, $limit))) { 
  9. if($breakpoint < strlen($string) - 1) { 
  10. $string = substr($string, 0, $breakpoint) . $pad; 
  11. return $string; 
  12. /***** Example ****/ 
  13. $short_string=myTruncate($long_string, 100, ' '); 

16. PHP文件 Zip 压缩

  1. /* creates a compressed zip file */ 
  2. function create_zip($files = array(),$destination = '',$overwrite = false) { 
  3. //if the zip file already exists and overwrite is false, return false 
  4. if(file_exists($destination) && !$overwrite) { return false; } 
  5. //vars 
  6. $valid_files = array(); 
  7. //if files were passed in... 
  8. if(is_array($files)) { 
  9. //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. //if we have good files... 
  15. if(count($valid_files)) { 
  16. //create the archive 
  17. $zip = new ZipArchive(); 
  18. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { 
  19. return false; 
  20. //add the files 
  21. foreach($valid_files as $file) { 
  22. $zip->addFile($file,$file); 
  23. //debug 
  24. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;  
  25. //close the zip -- done! 
  26. $zip->close();  
  27. //check to make sure the file exists 
  28. return file_exists($destination); 
  29. else 
  30. return false; 
  31. /***** Example Usage ***/ 
  32. $files=array('file1.jpg', 'file2.jpg', 'file3.gif'); 
  33. create_zip($files, 'myzipfile.zip', true); 

17. PHP解压缩 Zip 文件

  1. /********************** 
  2. *@file - path to zip file 
  3. *@destination - destination directory for unzipped files 
  4. */ 
  5. function unzip_file($file, $destination){ 
  6. // create object 
  7. $zip = new ZipArchive() ; 
  8. // open archive 
  9. if ($zip->open($file) !== TRUE) { 
  10. die (’Could not open archive’); 
  11. // extract contents to destination directory 
  12. $zip->extractTo($destination); 
  13. // close archive 
  14. $zip->close(); 
  15. echo 'Archive extracted to directory'; 

18. PHP为 URL 地址预设 http 字符串

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

  1. if (!preg_match("/^(http|ftp):/", $_POST['url'])) { 
  2. $_POST['url'] = 'http://'.$_POST['url']; 

19. PHP将网址字符串转换成超级链接

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

  1. function makeClickableLinks($text) { 
  2. $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', 
  3. '1', $text); 
  4. $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', 
  5. '12', $text); 
  6. $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', 
  7. '1', $text);  
  8. return $text; 

20. PHP调整图像尺寸

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

  1. /********************** 
  2. *@filename - path to the image 
  3. *@tmpname - temporary path to thumbnail 
  4. *@xmax - max width 
  5. *@ymax - max height 
  6. */ 
  7. function resize_image($filename, $tmpname, $xmax, $ymax) 
  8. $ext = explode(".", $filename); 
  9. $ext = $ext[count($ext)-1];   
  10. if($ext == "jpg" || $ext == "jpeg") 
  11. $im = imagecreatefromjpeg($tmpname); 
  12. elseif($ext == "png") 
  13. $im = imagecreatefrompng($tmpname); 
  14. elseif($ext == "gif") 
  15. $im = imagecreatefromgif($tmpname);   
  16. $x = imagesx($im); 
  17. $y = imagesy($im);   
  18. if($x <= $xmax && $y <= $ymax) 
  19. return $im;   
  20. if($x >= $y) { 
  21. $newx = $xmax; 
  22. $newy = $newx * $y / $x; 
  23. else { 
  24. $newy = $ymax; 
  25. $newx = $x / $y * $newy; 
  26. }   
  27. $im2 = imagecreatetruecolor($newx, $newy); 
  28. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y); 
  29. return $im2; 

21. PHP检测 ajax 请求

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

  1. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ 
  2. //If AJAX Request Then 
  3. }else

上一篇:有风险的架构是什么?

下一篇:企业网站建设对于企业的发展作用

发表评论:

评论记录:

未查询到任何数据!

在线咨询

点击这里给我发消息 售前咨询专员

点击这里给我发消息 售后服务专员

在线咨询

免费通话

24小时免费咨询

请输入您的联系电话,座机请加区号

免费通话

微信扫一扫

微信联系
返回顶部