實用的PHP實例代碼20個

讓珊瑚遠離驚濤駭浪的侵蝕嗎?那無異是將它們的美麗葬送。以下是小編爲大家搜索整理的實用的PHP實例代碼20個,希望能給大家帶來幫助!更多精彩內容請及時關注我們應屆畢業生考試網!

實用的PHP實例代碼20個

可閱讀隨機字符串

此代碼將創建一個可閱讀的字符串,使其更接近詞典中的單詞,實用且具有密碼驗證功能。

/**************
*@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(’@’,’&#64;’,$email);
$email=str_replace(’.’,’&#46;’,$email);
$email=str_split($email,5);

$linkText=str_replace(’@’,’&#64;’,$linkText);
$linkText=str_replace(’.’,’&#46;’,$linkText);
$linkText=str_split($linkText,5);

$part1=’<ahref="ma’;
$part2=’ilto&#58;’;
$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
}