1. PHP可閱讀隨機字串<br />此代碼將建立一個可閱讀的字串,使其更接近詞典中的單詞,實用且具有密碼驗證功能。<br />/**************<br />*@length - length of random string (must be a multiple of 2)<br />**************/<br />function readable_random_string($length = 6){<br /> $conso=array("b","c","d","f","g","h","j","k","l",<br /> "m","n","p","r","s","t","v","w","x","y","z");<br /> $vocal=array("a","e","i","o","u");<br /> $password="";<br /> srand ((double)microtime()*1000000);<br /> $max = $length/2;<br /> for($i=1; $i<=$max; $i++)<br /> {<br /> $password.=$conso[rand(0,19)];<br /> $password.=$vocal[rand(0,4)];<br /> }<br /> return $password;<br />}<br />2. PHP產生一個隨機字串<br />如果不需要可閱讀的字串,使用此函數替代,即可建立一個隨機字串,作為使用者的隨機密碼等。<br />/*************<br />*@l - length of random string<br />*/<br />function generate_rand($l){<br /> $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";<br /> srand((double)microtime()*1000000);<br /> for($i=0; $i<$l; $i++) {<br /> $rand.= $c[rand()%strlen($c)];<br /> }<br /> return $rand;<br /> }<br />3. PHP編碼電子郵件地址<br />使用此代碼,可以將任何電子郵件地址編碼為 html 字元實體,以防止被垃圾郵件程式收集。<br />function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )<br />{<br /> // remplazar aroba y puntos<br /> $email = str_replace('@', '@', $email);<br /> $email = str_replace('.', '.', $email);<br /> $email = str_split($email, 5);<br /> $linkText = str_replace('@', '@', $linkText);<br /> $linkText = str_replace('.', '.', $linkText);<br /> $linkText = str_split($linkText, 5);<br /> $part1 = '<a href="ma';<br /> $part2 = 'ilto:';<br /> $part3 = '" mce_href="ma';<br /> $part2 = 'ilto:';<br /> $part3 = '" '. $attrs .' >';<br /> $part4 = '</a>';<br /> $encoded = '<mce:script type="text/javascript"><!--<br />';<br /> $encoded .= "document.write('$part1');";<br /> $encoded .= "document.write('$part2');";<br /> foreach($email as $e)<br /> {<br /> $encoded .= "document.write('$e');";<br /> }<br /> $encoded .= "document.write('$part3');";<br /> foreach($linkText as $l)<br /> {<br /> $encoded .= "document.write('$l');";<br /> }<br /> $encoded .= "document.write('$part4');";<br /> $encoded .= '<br />// --></mce:script>';<br /> return $encoded;<br />}<br />4. PHP驗證郵件地址<br />電子郵件驗證也許是中最常用的網頁表單驗證,此代碼除了驗證電子郵件地址,也可以選擇檢查郵件域所屬 DNS 中的 MX 記錄,使郵件驗證功能更加強大。<br />function is_valid_email($email, $test_mx = false)<br />{<br /> if(eregi("^([_a-z0-9-]+)(/.[_a-z0-9-]+)*@([a-z0-9-]+)(/.[a-z0-9-]+)*(/.[a-z]{2,4})$", $email))<br /> if($test_mx)<br /> {<br /> list($username, $domain) = split("@", $email);<br /> return getmxrr($domain, $mxrecords);<br /> }<br /> else<br /> return true;<br /> else<br /> return false;<br />}<br />5. PHP列出目錄內容<br />function list_files($dir)<br />{<br /> if(is_dir($dir))<br /> {<br /> if($handle = opendir($dir))<br /> {<br /> while(($file = readdir($handle)) !== false)<br /> {<br /> if($file != "." && $file != ".." && $file != "Thumbs.db")<br /> {<br /> echo '<a target="_blank" href="'.$dir.$file.'" mce_href="'.$dir.$file.'">'.$file.'</a><br>'."/n";<br /> }<br /> }<br /> closedir($handle);<br /> }<br /> }<br />}<br />6. PHP銷毀目錄<br />刪除一個目錄,包括它的內容。<br />/*****<br />*@dir - Directory to destroy<br />*@virtual[optional]- whether a virtual directory<br />*/<br />function destroyDir($dir, $virtual = false)<br />{<br /> $ds = DIRECTORY_SEPARATOR;<br /> $dir = $virtual ? realpath($dir) : $dir;<br /> $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;<br /> if (is_dir($dir) && $handle = opendir($dir))<br /> {<br /> while ($file = readdir($handle))<br /> {<br /> if ($file == '.' || $file == '..')<br /> {<br /> continue;<br /> }<br /> elseif (is_dir($dir.$ds.$file))<br /> {<br /> destroyDir($dir.$ds.$file);<br /> }<br /> else<br /> {<br /> unlink($dir.$ds.$file);<br /> }<br /> }<br /> closedir($handle);<br /> rmdir($dir);<br /> return true;<br /> }<br /> else<br /> {<br /> return false;<br /> }<br />}<br />7. PHP解析 JSON 資料<br />與大多數流行的 Web 服務如 twitter 通過開放 API 來提供資料一樣,它總是能夠知道如何解析 API 資料的各種傳送格式,包括 JSON,XML 等等。<br />$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';<br />$obj=json_decode($json_string);<br />echo $obj->name; //prints foo<br />echo $obj->interest[1]; //prints php<br />8. PHP解析 XML 資料<br />//xml string<br />$xml_string="<?xml version='1.0'?><br /><users><br /> <user id='398'><br /> <name>Foo</name><br /> <email>foo@bar.com</name><br /> </user><br /> <user id='867'><br /> <name>Foobar</name><br /> <email>foobar@foo.com</name><br /> </user><br /></users>";<br />//load the xml string using simplexml<br />$xml = simplexml_load_string($xml_string);<br />//loop through the each node of user<br />foreach ($xml->user as $user)<br />{<br /> //access attribute<br /> echo $user['id'], ' ';<br /> //subnodes are accessed by -> operator<br /> echo $user->name, ' ';<br /> echo $user->email, '<br />';<br />}<br />9. PHP建立日誌縮減名<br />建立方便使用的日誌縮減名。<br />function create_slug($string){<br /> $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);<br /> return $slug;<br />}<br />10. PHP擷取用戶端真實 IP 位址<br />該函數將擷取使用者的真實 IP 位址,即便他使用Proxy 伺服器。<br />function getRealIpAddr()<br />{<br /> if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))<br /> {<br /> $ip=$_SERVER['HTTP_CLIENT_IP'];<br /> }<br /> elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))<br /> //to check ip is pass from proxy<br /> {<br /> $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];<br /> }<br /> else<br /> {<br /> $ip=$_SERVER['REMOTE_ADDR'];<br /> }<br /> return $ip;<br />}<br />11. PHP強制性檔案下載<br />為使用者提供強制性的檔案下載功能。<br />/********************<br />*@file - path to file<br />*/<br />function force_download($file)<br />{<br /> if ((isset($file))&&(file_exists($file))) {<br /> header("Content-length: ".filesize($file));<br /> header('Content-Type: application/octet-stream');<br /> header('Content-Disposition: attachment; filename="' . $file . '"');<br /> readfile("$file");<br /> } else {<br /> echo "No file selected";<br /> }<br />}<br />12. PHP建立標籤雲<br />function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )<br />{<br /> $minimumCount = min( array_values( $data ) );<br /> $maximumCount = max( array_values( $data ) );<br /> $spread = $maximumCount - $minimumCount;<br /> $cloudHTML = '';<br /> $cloudTags = array();<br /> $spread == 0 && $spread = 1;<br /> foreach( $data as $tag => $count )<br /> {<br /> $size = $minFontSize + ( $count - $minimumCount )<br /> * ( $maxFontSize - $minFontSize ) / $spread;<br /> $cloudTags[] = '<a style="font-size: ' . floor( $size ) . 'px'<br /> . '" mce_style="font-size: ' . floor( $size ) . 'px'<br /> . '" href="#" mce_href="#" title="/'' . $tag .<br /> '/' returned a count of ' . $count . '">'<br /> . htmlspecialchars( stripslashes( $tag ) ) . '</a>';<br /> }<br /> return join( "/n", $cloudTags ) . "/n";<br />}<br />/**************************<br />**** Sample usage ***/<br />$arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,<br /> 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,<br /> 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,<br /> 'Extract' => 28, 'Filters' => 42);<br />echo getCloud($arr, 12, 36);<br />13. PHP尋找兩個字串的相似性<br />PHP 提供了一個極少使用的 similar_text 函數,但此函數非常有用,用於比較兩個字串並返回相似程度的百分比。<br />similar_text($string1, $string2, $percent);<br />//$percent will have the percentage of similarity<br />14. PHP在應用程式中使用 Gravatar 通用頭像<br />隨著 WordPress 越來越普及,Gravatar 也隨之流行。由於 Gravatar 提供了便於使用的 API,將其納入應用程式也變得十分方便。<br />/******************<br />*@email - Email address to show gravatar for<br />*@size - size of gravatar<br />*@default - URL of default gravatar to use<br />*@rating - rating of Gravatar(G, PG, R, X)<br />*/<br />function show_gravatar($email, $size, $default, $rating)<br />{<br /> echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).<br /> '&default='.$default.'&size='.$size.'&rating='.$rating.'" mce_src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email).<br /> '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px"<br /> height="'.$size.'px" />';<br />}<br />15. PHP在字元斷點處截斷文字<br />所謂斷字 (word break),即一個單詞可在轉行時斷開的地方。這一函數將在斷字處截斷字串。<br />// Original PHP code by Chirp Internet: www.chirp.com.au<br />// Please acknowledge use of this code by including this header.<br />function myTruncate($string, $limit, $break=".", $pad="...") {<br /> // return with no change if string is shorter than $limit<br /> if(strlen($string) <= $limit)<br /> return $string;<br /> // is $break present between $limit and the end of the string?<br /> if(false !== ($breakpoint = strpos($string, $break, $limit))) {<br /> if($breakpoint < strlen($string) - 1) {<br /> $string = substr($string, 0, $breakpoint) . $pad;<br /> }<br /> }<br /> return $string;<br />}<br />/***** Example ****/<br />$short_string=myTruncate($long_string, 100, ' ');<br />16. PHP檔案 Zip 壓縮<br />/* creates a compressed zip file */<br />function create_zip($files = array(),$destination = '',$overwrite = false) {<br /> //if the zip file already exists and overwrite is false, return false<br /> if(file_exists($destination) && !$overwrite) { return false; }<br /> //vars<br /> $valid_files = array();<br /> //if files were passed in...<br /> if(is_array($files)) {<br /> //cycle through each file<br /> foreach($files as $file) {<br /> //make sure the file exists<br /> if(file_exists($file)) {<br /> $valid_files[] = $file;<br /> }<br /> }<br /> }<br /> //if we have good files...<br /> if(count($valid_files)) {<br /> //create the archive<br /> $zip = new ZipArchive();<br /> if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {<br /> return false;<br /> }<br /> //add the files<br /> foreach($valid_files as $file) {<br /> $zip->addFile($file,$file);<br /> }<br /> //debug<br /> //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;<br /> //close the zip -- done!<br /> $zip->close();<br /> //check to make sure the file exists<br /> return file_exists($destination);<br /> }<br /> else<br /> {<br /> return false;<br /> }<br />}<br />/***** Example Usage ***/<br />$files=array('file1.jpg', 'file2.jpg', 'file3.gif');<br />create_zip($files, 'myzipfile.zip', true);<br />17. PHP解壓縮 Zip 檔案<br />/**********************<br />*@file - path to zip file<br />*@destination - destination directory for unzipped files<br />*/<br />function unzip_file($file, $destination){<br /> // create object<br /> $zip = new ZipArchive() ;<br /> // open archive<br /> if ($zip->open($file) !== TRUE) {<br /> die (’Could not open archive’);<br /> }<br /> // extract contents to destination directory<br /> $zip->extractTo($destination);<br /> // close archive<br /> $zip->close();<br /> echo 'Archive extracted to directory';<br />}<br />18. PHP為 URL 地址預設 http 字串<br />有時需要接受一些表單中的網址輸入,但使用者很少添加 http:// 欄位,此代碼將為網址添加該欄位。<br />if (!preg_match("/^(http|ftp):/", $_POST['url'])) {<br /> $_POST['url'] = 'http://'.$_POST['url'];<br />}<br />19. PHP將網址字串轉換成超級連結<br />該函數將 URL 和 E-mail 地址字串轉換為可點擊的超級連結。<br />function makeClickableLinks($text) {<br /> $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',<br /> '<a href="/1" mce_href="/1">/1</a>', $text);<br /> $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',<br /> '/1<a href="http:///2" mce_href="http:///2">/2</a>', $text);<br /> $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',<br /> '<a href="mailto:/1" mce_href="mailto:/1">/1</a>', $text);<br />return $text;<br />}<br />20. PHP調整映像尺寸<br />建立映像縮圖需要許多時間,此代碼將有助於瞭解縮圖的邏輯。<br />/**********************<br />*@filename - path to the image<br />*@tmpname - temporary path to thumbnail<br />*@xmax - max width<br />*@ymax - max height<br />*/<br />function resize_image($filename, $tmpname, $xmax, $ymax)<br />{<br /> $ext = explode(".", $filename);<br /> $ext = $ext[count($ext)-1];<br /> if($ext == "jpg" || $ext == "jpeg")<br /> $im = imagecreatefromjpeg($tmpname);<br /> elseif($ext == "png")<br /> $im = imagecreatefrompng($tmpname);<br /> elseif($ext == "gif")<br /> $im = imagecreatefromgif($tmpname);<br /> $x = imagesx($im);<br /> $y = imagesy($im);<br /> if($x <= $xmax && $y <= $ymax)<br /> return $im;<br /> if($x >= $y) {<br /> $newx = $xmax;<br /> $newy = $newx * $y / $x;<br /> }<br /> else {<br /> $newy = $ymax;<br /> $newx = $x / $y * $newy;<br /> }<br /> $im2 = imagecreatetruecolor($newx, $newy);<br /> imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);<br /> return $im2;<br />}<br />21. PHP檢測 ajax 請求<br />大多數的 JavaScript 架構如 jquery,Mootools 等,在發出 Ajax 請求時,都會發送額外的 HTTP_X_REQUESTED_WITH 頭部資訊,頭當他們一個ajax請求,因此你可以在伺服器端偵測到 Ajax 請求。<br />if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){<br /> //If AJAX Request Then<br />}else{<br />//something else<br />}