Web开发者必备:21个超实用PHP代码

1. PHP可阅读随机字符串

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

 
  1. /***************
  2. @length-lengthofrandomstring(mustbeamultipleof2)**************/
  3. functionreadable_random_string($length=6){
  4. $conso=array("b","c","d","f","g","h","j","k","l",
  5. "m","n","p","r","s","t","v","w","x","y","z");
  6. $vocal=array("a","e","i","o","u");
  7. $password="";
  8. srand((double)microtime()*1000000);
  9. $max=$length/2;
  10. for($i=1;
  11. $i<=$max;$i++)
  12. {
  13. $password.=$conso[rand(0,19)];
  14. $password.=$vocal[rand(0,4)];
  15. }
  16. return$password;
  17. }


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

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

 
  1. /*************
  2. *@l-lengthofrandomstring
  3. */
  4. functiongenerate_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 字符实体,以防止被垃圾邮件程序收集。

 
  1. functionencode_email($email='info@domain.com',$linkText='ContactUs',$attrs='class="emailencoder"')
  2. {
  3. //remplazararobaypuntos
  4. $email=str_replace('@','@',$email);
  5. $email=str_replace('.','.',$email);
  6. $email=str_split($email,5);
  7. $linkText=str_replace('@','@',$linkText);
  8. $linkText=str_replace('.','.',$linkText);
  9. $linkText=str_split($linkText,5);$part1='part2='ilto:';$part3='"'.$attrs.'>';
  10. $part4='';
  11. $encoded='';
  12. $encoded.="document.write('$part1');";
  13. $encoded.="document.write('$part2');";
  14. foreach($emailas$e)
  15. {
  16. $encoded.="document.write('$e');";
  17. }
  18. $encoded.="document.write('$part3');";
  19. foreach($linkTextas$l)
  20. {
  21. $encoded.="document.write('$l');";
  22. }
  23. $encoded.="document.write('$part4');";
  24. $encoded.='';return$encoded;}


4. PHP验证邮件地址

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

 
  1. functionis_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))if($test_mx)
  4. {
  5. list($username,$domain)=split("@",$email);
  6. returngetmxrr($domain,$mxrecords);
  7. }
  8. else
  9. returntrue;
  10. else
  11. returnfalse;
  12. }

    5. PHP列出目录内容

     
      
    1. functionlist_files($dir){
    2. if(is_dir($dir))
    3. {
    4. if($handle=opendir($dir)){
    5. while(($file=readdir($handle))!==false)
    6. {
    7. if($file!="."&&$file!=".."&&$file!="Thumbs.db")
    8. {echo'<atarget="_blank"href="'.$dir.$file.'">'.$file.'a><br>'."\n";
    9. }
    10. }
    11. closedir($handle);
    12. }
    13. }
    14. }


    6. PHP销毁目录

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

     
      
    1. /*****
    2. *@dir-Directorytodestroy
    3. *@virtual[optional]-whetheravirtualdirectory
    4. */
    5. functiondestroyDir($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. returntrue;
    30. }
    31. else
    32. {
    33. returnfalse;
    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);
    3. echo$obj->name;//printsfoo
    4. echo$obj->interest[1];//printsphp


    8. PHP解析 XML 数据

     
      
    1. //xmlstring
    2. $xml_string="xmlversion='1.0'?>
    3. <users>
    4. <userid='398'>
    5. <name>Fooname>
    6. <email>foo@bar.comname>
    7. user>
    8. <userid='867'>
    9. <name>Foobarname>
    10. <email>foobar@foo.comname>
    11. user>users>";
    12. //loadthexmlstringusingsimplexml
    13. $xml=simplexml_load_string($xml_string);
    14. //loopthroughtheeachnodeofuser
    15. foreach($xml->useras$user)
    16. {
    17. //accessattribute
    18. echo$user['id'],'';
    19. //subnodesareaccessedby->operator
    20. echo$user->name,'';
    21. echo$user->email,'<br/>';
    22. }
    9. PHP创建日志缩略名

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

     
      
    1. functioncreate_slug($string){
    2. $slug=preg_replace('/[^A-Za-z0-9-]+/','-',$string);
    3. return$slug;
    4. }

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

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

     
      
    1. functiongetRealIpAddr()
    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. //tocheckipispassfromproxy
    9. {
    10. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    11. }
    12. else
    13. {
    14. $ip=$_SERVER['REMOTE_ADDR'];
    15. }
    16. return$ip;
    17. }


    11. PHP强制性文件下载

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

     
      
    1. /********************
    2. *@file-pathtofile
    3. */
    4. functionforce_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. }
    12. else{
    13. echo"Nofileselected";
    14. }
    15. }


    12. PHP创建标签云

     
      
    1. functiongetCloud($data=array(),$minFontSize=12,$maxFontSize=30)
    2. {
    3. $minminimumCount=min(array_values($data));
    4. $maxmaximumCount=max(array_values($data));
    5. $spread=$maximumCount-$minimumCount;$cloudHTML='';
    6. $cloudTags=array();
    7. $spread==0&&$spread=1;
    8. foreach($dataas$tag=>$count)
    9. {
    10. $size=$minFontSize+($count-$minimumCount)*($maxFontSize-$minFontSize)/$spread;
    11. $cloudTags[]='<astyle="font-size:'.floor($size).'px'
    12. .'"href="#"title="\''.$tag.
    13. '\'returnedacountof'.$count.'">'
    14. .htmlspecialchars(stripslashes($tag)).'a>';
    15. }
    16. returnjoin("\n",$cloudTags)."\n";
    17. }
    18. /***************************
    19. ***Sampleusage***/
    20. $arr=Array('Actionscript'=>35,'Adobe'=>22,'Array'=>44,'Background'=>43,
    21. 'Blur'=>18,'Canvas'=>33,'Class'=>15,'ColorPalette'=>11,'Crop'=>42,
    22. 'Delimiter'=>13,'Depth'=>34,'Design'=>8,'Encode'=>12,'Encryption'=>30,
    23. 'Extract'=>28,'Filters'=>42);
    24. echogetCloud($arr,12,36);


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

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

     
      
    1. similar_text($string1,$string2,$percent);
    2. //$percentwillhavethepercentageofsimilarity

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

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

     
      
    1. /******************
    2. *@email-Emailaddresstoshowgravatarfor
    3. *@size-sizeofgravatar
    4. *@default-URLofdefaultgravatartouse
    5. *@rating-ratingofGravatar(G,PG,R,X)
    6. */
    7. functionshow_gravatar($email,$size,$default,$rating)
    8. {
    9. echo'<imgsrc="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),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。

     
      
    1. //OriginalPHPcodebyChirpInternet:www.chirp.com.au
    2. //Pleaseacknowledgeuseofthiscodebyincludingthisheader.
    3. functionmyTruncate($string,$limit,$break=".",$pad="..."){
    4. //returnwithnochangeifstringisshorterthan$limit
    5. if(strlen($string)<=$limit)
    6. return$string;
    7. //is$breakpresentbetween$limitandtheendofthestring?
    8. if(false!==($breakpoint=strpos($string,$break,$limit))){
    9. if($breakpoint<strlen($string)-1){
    10. $string=substr($string,0,$breakpoint).$pad;
    11. }
    12. }
    13. return$string;
    14. }
    15. /*****Example****/
    16. $short_string=myTruncate($long_string,100,'');


    16. PHP文件 Zip 压缩

     
      
    1. /*createsacompressedzipfile*/
    2. functioncreate_zip($files=array(),$destination='',$overwrite=false){
    3. //ifthezipfilealreadyexistsandoverwriteisfalse,returnfalse
    4. if(file_exists($destination)&&!$overwrite){returnfalse;}
    5. //vars$valid_files=array();
    6. //iffileswerepassedin...
    7. if(is_array($files)){
    8. //cyclethrougheachfile
    9. foreach($filesas$file){
    10. //makesurethefileexists
    11. if(file_exists($file)){
    12. $valid_files[]=$file;
    13. }
    14. }
    15. }
    16. //ifwehavegoodfiles...
    17. if(count($valid_files)){
    18. //createthearchive
    19. $zip=newZipArchive();
    20. if($zip->open($destination,$overwrite?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)!==true){returnfalse;
    21. }
    22. //addthefiles
    23. foreach($valid_filesas$file){
    24. $zip->addFile($file,$file);
    25. }
    26. //debug//echo'Theziparchivecontains',$zip->numFiles,'fileswithastatusof',$zip->status;
    27. //closethezip--done!
    28. $zip->close();
    29. //checktomakesurethefileexists
    30. returnfile_exists($destination);
    31. }
    32. else
    33. {
    34. returnfalse;
    35. }
    36. }
    37. /*****ExampleUsage***/
    38. $files=array('file1.jpg','file2.jpg','file3.gif');
    39. create_zip($files,'myzipfile.zip',true);


    17. PHP解压缩 Zip 文件

     
      
    1. /**********************
    2. *@file-pathtozipfile
    3. *@destination-destinationdirectoryforunzippedfiles
    4. */
    5. functionunzip_file($file,$destination){
    6. //createobject
    7. $zip=newZipArchive();
    8. //openarchive
    9. if($zip->open($file)!==TRUE){
    10. die(’Couldnotopenarchive’);
    11. }
    12. //extractcontentstodestinationdirectory
    13. $zip->extractTo($destination);
    14. //closearchive
    15. $zip->close();
    16. echo'Archiveextractedtodirectory';
    17. }

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

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

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

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

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

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

    20. PHP调整图像尺寸

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

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

    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. //IfAJAXRequestThen
    3. }else{
    4. //somethingelse
    5. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值