可閱讀隨機字串
此程式碼將建立一個可閱讀的字串,使其更接近詞典中的單詞,實用且具有密碼驗證功能。
/************** *@length-lengthofrandomstring(mustbeamultipleof2) **************/ functionreadable_random_string($length=6){ $conso=array("b","c","d","f","g","h","j","k","l", "m","n","p","r","s","t","v","w","x","y","z"); $vocal=array("a","e","i","o","u"); $password=""; srand((double)microtime()*1000000); $max=$length/2; for($i=1;$i<=$max;$i++) { $password.=$conso[rand(0,19)]; $password.=$vocal[rand(0,4)]; } return$password; }
生成一個隨機字串
如果不需要可閱讀的`字串,使用此函式替代,即可建立一個隨機字串,作為使用者的隨機密碼等。 /************* *@l-lengthofrandomstring */ functiongenerate_rand($l){ $c="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; srand((double)microtime()*1000000); for($i=0;$i<$l;$i++){ $rand.=$c[rand()%strlen($c)]; } return$rand; }
編碼電子郵件地址
使用此程式碼,可以將任何電子郵件地址編碼為html字元實體,以防止被垃圾郵件程式收集。
functionencode_email($’,$linkText=’ContactUs’,$attrs=’class="emailencoder"’) { //remplazararobaypuntos $email=str_replace(’@’,’@’,$email); $email=str_replace(’.’,’.’,$email); $email=str_split($email,5);
$linkText=str_replace(’@’,’@’,$linkText); $linkText=str_replace(’.’,’.’,$linkText); $linkText=str_split($linkText,5);
$part1=’<ahref="ma’; $part2=’ilto:’; $part3=’"’.$attrs.’>’; $part4=’</a>’;
$encoded=’<scripttype="text/javascript">’; $encoded.="e(’$part1’);"; $encoded.="e(’$part2’);"; foreach($emailas$e) { $encoded.="e(’$e’);"; } $encoded.="e(’$part3’);"; foreach($linkTextas$l) { $encoded.="e(’$l’);"; } $encoded.="e(’$part4’);"; $encoded.=’</script>’;
return$encoded; }
驗證郵件地址
電子郵件驗證也許是中最常用的網頁表單驗證,此程式碼除了驗證電子郵件地址,也可以選擇檢查郵件域所屬DNS中的MX記錄,使郵件驗證功能更加強大。
functionis_valid_email($email,$test_mx=false) { if(eregi("^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$",$email)) if($test_mx) { list($username,$domain)=split("@",$email); returngetmxrr($domain,$mxrecords); } else returntrue; else returnfalse; }
列出目錄內容
functionlist_files($dir) { if(is_dir($dir)) { if($handle=opendir($dir)) { while(($file=readdir($handle))!==false) { if($file!="."&&$file!=".."&&$file!="") { echo’<atarget="_blank"href="’.$dir.$file.’">’.$file.’</a><br>’."n"; } } closedir($handle); } } }
銷燬目錄
刪除一個目錄,包括它的內容。
/***** *@dir-Directorytodestroy *@virtual[optional]-whetheravirtualdirectory */ functiondestroyDir($dir,$virtual=false) { $ds=DIRECTORY_SEPARATOR; $dir=$virtual?realpath($dir):$dir; $dir=substr($dir,-1)==$ds?substr($dir,0,-1):$dir; if(is_dir($dir)&&$handle=opendir($dir)) { while($file=readdir($handle)) { if($file==’.’||$file==’..’) { continue; } elseif(is_dir($dir.$ds.$file)) { destroyDir($dir.$ds.$file); } else { unlink($dir.$ds.$file); } } closedir($handle); rmdir($dir); returntrue; } else { returnfalse; } }
解析JSON資料
與大多數流行的Web服務如twitter通過開放API來提供資料一樣,它總是能夠知道如何解析API資料的各種傳送格式,包括JSON,XML等等。
$json_string=’{"id":1,"name":","interest":["wordpress","php"]}’; $obj=json_decode($json_string); echo$obj->name;//printsfoo echo$obj->interest[1];//printsphp
解析XML資料
//xmlstring $xml_string="<?xmlversion=’1.0’?> <users> <userid=’398’> <name>Foo</name> </name> </user> <userid=’867’> <name>Foobar</name> </name> </user> </users>";
//loadthexmlstringusingsimplexml $xml=simplexml_load_string($xml_string);
//loopthroughtheeachnodeofuser foreach($xml->useras$user) { //accessattribute echo$user[’id’],’’; //subnodesareaccessedby->operator echo$user->name,’’; echo$user->email,’<br/>’; }
建立日誌縮略名
建立使用者友好的日誌縮略名。
functioncreate_slug($string){ $slug=preg_replace(’/[^A-Za-z0-9-]+/’,’-’,$string); return$slug; }
獲取客戶端真實IP地址
該函式將獲取使用者的真實IP地址,即便他使用代理伺服器。
functiongetRealIpAddr() { if(!emptyempty($_SERVER[’HTTP_CLIENT_IP’])) { $ip=$_SERVER[’HTTP_CLIENT_IP’]; } elseif(!emptyempty($_SERVER[’HTTP_X_FORWARDED_FOR’])) //tocheckipispassfromproxy { $ip=$_SERVER[’HTTP_X_FORWARDED_FOR’]; } else { $ip=$_SERVER[’REMOTE_ADDR’]; } return$ip; }
強制性檔案下載
為使用者提供強制性的檔案下載功能。
/******************** *@file-pathtofile */ functionforce_download($file) { if((isset($file))&&(file_exists($file))){ header("Content-length:"size($file)); header(’Content-Type:application/octet-stream’); header(’Content-Disposition:attachment;filename="’.$file.’"’); readfile("$file"); }else{ echo"Nofileselected"; } } 建立標籤雲 functiongetCloud($data=array(),$minFontSize=12,$maxFontSize=30) { $minimumCount=min(array_values($data)); $maximumCount=max(array_values($data)); $spread=$maximumCount-$minimumCount; $cloudHTML=’’; $cloudTags=array();
$spread==0&&$spread=1;
foreach($dataas$tag=>$count) { $size=$minFontSize+($count-$minimumCount) *($maxFontSize-$minFontSize)/$spread; $cloudTags[]=’<astyle="font-size:’r($size).’px’ .’"href="#"title="’’.$tag. ’’returnedacountof’.$count.’">’ specialchars(stripslashes($tag)).’</a>’; }
returnjoin("n",$cloudTags)."n"; } /************************** ****Sampleusage***/ $arr=Array(’Actionscript’=>35,’Adobe’=>22,’Array’=>44,’Background’=>43, ’Blur’=>18,’Canvas’=>33,’Class’=>15,’ColorPalette’=>11,’Crop’=>42, ’Delimiter’=>13,’Depth’=>34,’Design’=>8,’Encode’=>12,’Encryption’=>30, ’Extract’=>28,’Filters’=>42); echogetCloud($arr,12,36);
尋找兩個字串的相似性
PHP提供了一個極少使用的similar_text函式,但此函式非常有用,用於比較兩個字串並返回相似程度的百分比。 similar_text($string1,$string2,$percent); //$percentwillhavethepercentageofsimilarity
在應用程式中使用Gravatar通用頭像
隨著WordPress越來越普及,Gravatar也隨之流行。由於Gravatar提供了易於使用的API,將其納入應用程式也變得十分方便。
/****************** *@email-Emailaddresstoshowgravatarfor *@size-sizeofgravatar *@default-URLofdefaultgravatartouse *@rating-ratingofGravatar(G,PG,R,X) */ functionshow_gravatar($email,$size,$default,$rating) { echo’<imgsrc="_id=’5($email). ’&default=’.$default.’&size=’.$size.’&rating=’.$rating.’"width="’.$size.’px" height="’.$size.’px"/>’; }
在字元斷點處截斷文字
所謂斷字(wordbreak),即一個單詞可在轉行時斷開的地方。這一函式將在斷字處截斷字串。
//OriginalPHPcodebyChirpInternet: //Pleaseacknowledgeuseofthiscodebyincludingthisheader. functionmyTruncate($string,$limit,$break=".",$pad="..."){ //returnwithnochangeifstringisshorterthan$limit if(strlen($string)<=$limit) return$string;
//is$breakpresentbetween$limitandtheendofthestring? if(false!==($breakpoint=strpos($string,$break,$limit))){ if($breakpoint<strlen($string)-1){ $string=substr($string,0,$breakpoint).$pad; } } return$string; } /*****Example****/ $short_string=myTruncate($long_string,100,’’);
檔案Zip壓縮
/*createsacompressedzipfile*/ functioncreate_zip($files=array(),$destination=’’,$overwrite=false){ //ifthezipfilealreadyexistsandoverwriteisfalse,returnfalse if(file_exists($destination)&&!$overwrite){returnfalse;} //vars $valid_files=array(); //iffileswerepassedin... if(is_array($files)){ //cyclethrougheachfile foreach($filesas$file){ //makesurethefileexists if(file_exists($file)){ $valid_files[]=$file; } } } //ifwehavegoodfiles... if(count($valid_files)){ //createthearchive $zip=newZipArchive(); if($zip->open($destination,$overwrite?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)!==true){ returnfalse; } //addthefiles foreach($valid_filesas$file){ $zip->addFile($file,$file); } //debug //echo’Theziparchivecontains’,$zip->numFiles,’fileswithastatusof’,$zip->status;
//closethezip--done! $zip->close();
//checktomakesurethefileexists returnfile_exists($destination); } else { returnfalse; } } /*****ExampleUsage***/ $files=array(’file1.jpg’,’file2.jpg’,’file3.gif’); create_zip($files,’’,true);
解壓縮Zip檔案
/********************** *@file-pathtozipfile *@destination-destinationdirectoryforunzippedfiles */ functionunzip_file($file,$destination){ //createobject $zip=newZipArchive(); //openarchive if($zip->open($file)!==TRUE){ die(’Couldnotopenarchive’); } //extractcontentstodestinationdirectory $zip->extractTo($destination); //closearchive $zip->close(); echo’Archiveextractedtodirectory’; } 為URL地址預設http字串
有時需要接受一些表單中的網址輸入,但使用者很少新增http://欄位,此程式碼將為網址新增該欄位。
if(!preg_match("/^(http|ftp):/",$_POST[’url’])){ $_POST[’url’]=’http://’.$_POST[’url’]; }
將網址字串轉換成超級連結
該函式將URL和E-mail地址字串轉換為可點選的超級連結。
functionmakeClickableLinks($text){$text=eregi_replace(’(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,’<ahref="1">1</a>’,$text);$text=eregi_replace(’([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,’1<ahref="http://2">2</a>’,$text);$text=eregi_replace(’([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,’<ahref="mailto:1">1</a>’,$text);return$text;}
調整影象尺寸
建立影象縮圖需要許多時間,此程式碼將有助於瞭解縮圖的邏輯。
/********************** *@filename-pathtotheimage *@tmpname-temporarypathtothumbnail *@xmax-maxwidth *@ymax-maxheight */ functionresize_image($filename,$tmpname,$xmax,$ymax) { $ext=explode(".",$filename); $ext=$ext[count($ext)-1];
if($ext=="jpg"||$ext=="jpeg") $im=imagecreatefromjpeg($tmpname); elseif($ext=="png") $im=imagecreatefrompng($tmpname); elseif($ext=="gif") $im=imagecreatefromgif($tmpname);
$x=imagesx($im); $y=imagesy($im);
if($x<=$xmax&&$y<=$ymax) return$im;
if($x>=$y){ $newx=$xmax; $newy=$newx*$y/$x; } else{ $newy=$ymax; $newx=$x/$y*$newy; }
$im2=imagecreatetruecolor($newx,$newy); imagecopyresized($im2,$im,0,0,0,0,floor($newx),floor($newy),$x,$y); return$im2; }
檢測ajax請求
大多數的JavaScript框架如jquery,Mootools等,在發出Ajax請求時,都會發送額外的HTTP_X_REQUESTED_WITH頭部資訊,頭當他們一個ajax請求,因此你可以在伺服器端偵測到Ajax請求。
if(!emptyempty($_SERVER[’HTTP_X_REQUESTED_WITH’])&&strtolower($_SERVER[’HTTP_X_REQUESTED_WITH’])==’xmlhttprequest’){ //IfAJAXRequestThen }else{ //somethingelse } |