MENU 服務(wù) 案例
網(wǎng)站建設(shè)-網(wǎng)站設(shè)計(jì)-北京網(wǎng)站建設(shè)-高端網(wǎng)站制作公司-尚品中國(guó)
我們通過(guò)擁抱變化創(chuàng)造
360°的品牌價(jià)值__
簡(jiǎn)體
簡(jiǎn)體中文 English

尚品簽約辰欣藥業(yè)股份有限公司官網(wǎng)建設(shè)

類(lèi)型:尚品動(dòng)態(tài) 了解更多

[北京網(wǎng)站制作]PHP二十一段救命代碼

來(lái)源:尚品中國(guó)| 類(lèi)型:網(wǎng)站百科| 時(shí)間:2011-10-21

1. PHP可閱讀隨機(jī)字符串

  此代碼將創(chuàng)建一個(gè)可閱讀的字符串,使其更接近詞典中的單詞,實(shí)用且具有密碼驗(yàn)證功能。

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

2. PHP生成一個(gè)隨機(jī)字符串

  如果不需要可閱讀的字符串,使用此函數(shù)替代,即可創(chuàng)建一個(gè)隨機(jī)字符串,作為用戶(hù)的隨機(jī)密碼等。

  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.   } 
  10.   return $rand

3. PHP編碼電子郵件地址

  使用此代碼,可以將任何電子郵件地址編碼為 html 字符實(shí)體,以防止被垃圾郵件程序收集。

  1. function encode_email($email='info@domain.com'$linkText='Contact Us'$attrs ='class="emailencoder"' ) 
  2.     // remplazar aroba y puntos 
  3.     $email = str_replace('@''&#64;'$email); 
  4.     $email = str_replace('.''&#46;'$email); 
  5.     $email = str_split($email, 5);   
  6.  
  7.     $linkText = str_replace('@''&#64;'$linkText); 
  8.     $linkText = str_replace('.''&#46;'$linkText); 
  9.     $linkText = str_split($linkText, 5);   
  10.  
  11.     $part1 = '<a href="ma'
  12.     $part2 = 'ilto&#58;'
  13.     $part3 = '" '$attrs .' >'
  14.     $part4 = '</a>';   
  15.  
  16.     $encoded = '<script type="text/javascript">'
  17.     $encoded .= "document.write('$part1');"
  18.     $encoded .= "document.write('$part2');"
  19.     foreach($email as $e
  20.     { 
  21.             $encoded .= "document.write('$e');"
  22.     } 
  23.     $encoded .= "document.write('$part3');"
  24.     foreach($linkText as $l
  25.     { 
  26.             $encoded .= "document.write('$l');"
  27.     } 
  28.     $encoded .= "document.write('$part4');"
  29.     $encoded .= '</script>';   
  30.  
  31.     return $encoded

4. PHP驗(yàn)證郵件地址

  電子郵件驗(yàn)證也許是中最常用的網(wǎng)頁(yè)表單驗(yàn)證,此代碼除了驗(yàn)證電子郵件地址,也可以選擇檢查郵件域所屬 DNS 中的 MX 記錄,使郵件驗(yàn)證功能更加強(qiáng)大。

  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.         { 
  5.             list($username$domain) = split("@"$email); 
  6.             return getmxrr($domain$mxrecords); 
  7.         } 
  8.         else 
  9.             return true; 
  10.     else 
  11.         return false; 

5. PHP列出目錄內(nèi)容

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

6. PHP銷(xiāo)毀目錄

  刪除一個(gè)目錄,包括它的內(nèi)容。

  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.     { 
  11.         while ($file = readdir($handle)) 
  12.         { 
  13.             if ($file == '.' || $file == '..'
  14.             { 
  15.                 continue
  16.             } 
  17.             elseif (is_dir($dir.$ds.$file)) 
  18.             { 
  19.                 destroyDir($dir.$ds.$file); 
  20.             } 
  21.             else 
  22.             { 
  23.                 unlink($dir.$ds.$file); 
  24.             } 
  25.         } 
  26.         closedir($handle); 
  27.         rmdir($dir); 
  28.         return true; 
  29.     } 
  30.     else 
  31.     { 
  32.         return false; 
  33.     } 

7. PHP解析 JSON 數(shù)據(jù)

  與大多數(shù)流行的 Web 服務(wù)如 twitter 通過(guò)開(kāi)放 API 來(lái)提供數(shù)據(jù)一樣,它總是能夠知道如何解析 API 數(shù)據(jù)的各種傳送格式,包括 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 數(shù)據(jù)

  1. //xml string 
  2. $xml_string="<?xml version='1.0'?> 
  3. <users> 
  4. <user id='398'
  5. <name>Foo</name> 
  6. <email>foo@bar.com</name> 
  7. </user> 
  8. <user id='867'
  9. <name>Foobar</name> 
  10. <email>foobar@foo.com</name> 
  11. </user> 
  12. </users>";  
  13.  
  14. //load the xml string using simplexml 
  15. $xml = simplexml_load_string($xml_string);  
  16.  
  17. //loop through the each node of user 
  18. foreach ($xml->user as $user
  19. //access attribute 
  20. echo $user['id'], ' '
  21. //subnodes are accessed by -> operator 
  22. echo $user->name, ' '
  23. echo $user->email, '<br />'

9. PHP創(chuàng)建日志縮略名

  創(chuàng)建用戶(hù)友好的日志縮略名。

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

10. PHP獲取客戶(hù)端真實(shí) IP 地址

  該函數(shù)將獲取用戶(hù)的真實(shí) IP 地址,即便他使用代理服務(wù)器。

  1. function getRealIpAddr() 
  2.     if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) 
  3.     { 
  4.         $ip=$_SERVER['HTTP_CLIENT_IP']; 
  5.     } 
  6.     elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) 
  7.     //to check ip is pass from proxy 
  8.     { 
  9.         $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; 
  10.     } 
  11.     else 
  12.     { 
  13.         $ip=$_SERVER['REMOTE_ADDR']; 
  14.     } 
  15.     return $ip

11. PHP強(qiáng)制性文件下載

  為用戶(hù)提供強(qiáng)制性的文件下載功能。

  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創(chuàng)建標(biāo)簽云

  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.  
  8. $spread == 0 && $spread = 1;  
  9.  
  10. foreach$data as $tag => $count ) 
  11. $size = $minFontSize + ( $count - $minimumCount ) 
  12. * ( $maxFontSize - $minFontSize ) / $spread
  13. $cloudTags[] = '<a style="font-size: ' . floor$size ) . 'px' 
  14. '" href="#" title="'' . $tag . 
  15. '' returned a count of ' . $count . '">' 
  16. . htmlspecialchars( stripslashes$tag ) ) . '</a>'
  17. }  
  18.  
  19. return join( "n"$cloudTags ) . "n"
  20. /************************** 
  21. **** Sample usage ***/ 
  22. $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 
  23. 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 
  24. 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 
  25. 'Extract' => 28, 'Filters' => 42); 
  26. echo getCloud($arr, 12, 36); 

13. PHP尋找兩個(gè)字符串的相似性

  PHP 提供了一個(gè)極少使用的 similar_text 函數(shù),但此函數(shù)非常有用,用于比較兩個(gè)字符串并返回相似程度的百分比。

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

14. PHP在應(yīng)用程序中使用 Gravatar 通用頭像

  隨著 WordPress 越來(lái)越普及,Gravatar 也隨之流行。由于 Gravatar 提供了易于使用的 API,將其納入應(yīng)用程序也變得十分方便。

  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 '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email). 
  9. '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" 
  10. height="'.$size.'px" />'; 

15. PHP在字符斷點(diǎn)處截?cái)辔淖?/strong>

  所謂斷字 (word break),即一個(gè)單詞可在轉(zhuǎn)行時(shí)斷開(kāi)的地方。這一函數(shù)將在斷字處截?cái)嘧址?/p>

  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.  
  8. // is $break present between $limit and the end of the string? 
  9. if(false !== ($breakpoint = strpos($string$break$limit))) { 
  10. if($breakpoint < strlen($string) - 1) { 
  11. $string = substr($string, 0, $breakpoint) . $pad
  12. return $string
  13. /***** Example ****/ 
  14. $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.  
  26. //close the zip -- done! 
  27. $zip->close();  
  28.  
  29. //check to make sure the file exists 
  30. return file_exists($destination); 
  31. else 
  32. return false; 
  33. /***** Example Usage ***/ 
  34. $files=array('file1.jpg''file2.jpg''file3.gif'); 
  35. 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 地址預(yù)設(shè) http 字符串

  有時(shí)需要接受一些表單中的網(wǎng)址輸入,但用戶(hù)很少添加 http:// 字段,此代碼將為網(wǎng)址添加該字段。

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

19. PHP將網(wǎng)址字符串轉(zhuǎn)換成超級(jí)鏈接

  該函數(shù)將 URL 和 E-mail 地址字符串轉(zhuǎn)換為可點(diǎn)擊的超級(jí)鏈接。

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

20. PHP調(diào)整圖像尺寸

  創(chuàng)建圖像縮略圖需要許多時(shí)間,此代碼將有助于了解縮略圖的邏輯。

  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.  
  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.  
  18.     $x = imagesx($im); 
  19.     $y = imagesy($im);   
  20.  
  21.     if($x <= $xmax && $y <= $ymax
  22.         return $im;   
  23.  
  24.     if($x >= $y) { 
  25.         $newx = $xmax
  26.         $newy = $newx * $y / $x
  27.     } 
  28.     else { 
  29.         $newy = $ymax
  30.         $newx = $x / $y * $newy
  31.     }   
  32.  
  33.     $im2 = imagecreatetruecolor($newx$newy); 
  34.     imagecopyresized($im2$im, 0, 0, 0, 0, floor($newx), floor($newy), $x$y); 
  35.     return $im2

21. PHP檢測(cè) ajax 請(qǐng)求

大多數(shù)的 JavaScript 框架如 jquery,Mootools 等,在發(fā)出 Ajax 請(qǐng)求時(shí),都會(huì)發(fā)送額外的 HTTP_X_REQUESTED_WITH 頭部信息,頭當(dāng)他們一個(gè)ajax請(qǐng)求,因此你可以在服務(wù)器端偵測(cè)到 Ajax 請(qǐng)求。

  1. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){ 
  2.     //If AJAX Request Then 
  3. }else
    來(lái)源聲明:本文章系尚品中國(guó)編輯原創(chuàng)或采編整理,如需轉(zhuǎn)載請(qǐng)注明來(lái)自尚品中國(guó)。以上內(nèi)容部分(包含圖片、文字)來(lái)源于網(wǎng)絡(luò),如有侵權(quán),請(qǐng)及時(shí)與本站聯(lián)系(010-60259772)。
    TAG標(biāo)簽:

如果您的網(wǎng)站可以增加轉(zhuǎn)化次數(shù)并提高客戶(hù)滿(mǎn)意度,該怎么辦?

預(yù)約專(zhuān)業(yè)咨詢(xún)顧問(wèn)溝通!

*尚品專(zhuān)業(yè)顧問(wèn)將盡快與您聯(lián)系

免責(zé)聲明

非常感謝您訪(fǎng)問(wèn)我們的網(wǎng)站。在您使用本網(wǎng)站之前,請(qǐng)您仔細(xì)閱讀本聲明的所有條款。

1、本站部分內(nèi)容來(lái)源自網(wǎng)絡(luò),涉及到的部分文章和圖片版權(quán)屬于原作者,本站轉(zhuǎn)載僅供大家學(xué)習(xí)和交流,切勿用于任何商業(yè)活動(dòng)。

2、本站不承擔(dān)用戶(hù)因使用這些資源對(duì)自己和他人造成任何形式的損失或傷害。

3、本聲明未涉及的問(wèn)題參見(jiàn)國(guó)家有關(guān)法律法規(guī),當(dāng)本聲明與國(guó)家法律法規(guī)沖突時(shí),以國(guó)家法律法規(guī)為準(zhǔn)。

4、如果侵害了您的合法權(quán)益,請(qǐng)您及時(shí)與我們,我們會(huì)在第一時(shí)間刪除相關(guān)內(nèi)容!

聯(lián)系方式:010-60259772
電子郵件:394588593@qq.com

  • 電話(huà)咨詢(xún)

    全國(guó)服務(wù)熱線(xiàn)400-700-4979

  • 在線(xiàn)咨詢(xún)

  • 微信咨詢(xún)

    微信咨詢(xún)

現(xiàn)在就與專(zhuān)業(yè)咨詢(xún)顧問(wèn)溝通!

  • 全國(guó)服務(wù)熱線(xiàn)

    400-700-4979

  • 北京服務(wù)熱線(xiàn)

    010-60259772

信息保護(hù)中請(qǐng)放心填寫(xiě)
在線(xiàn)咨詢(xún)

免責(zé)聲明

非常感謝您訪(fǎng)問(wèn)我們的網(wǎng)站。在您使用本網(wǎng)站之前,請(qǐng)您仔細(xì)閱讀本聲明的所有條款。

1、本站部分內(nèi)容來(lái)源自網(wǎng)絡(luò),涉及到的部分文章和圖片版權(quán)屬于原作者,本站轉(zhuǎn)載僅供大家學(xué)習(xí)和交流,切勿用于任何商業(yè)活動(dòng)。

2、本站不承擔(dān)用戶(hù)因使用這些資源對(duì)自己和他人造成任何形式的損失或傷害。

3、本聲明未涉及的問(wèn)題參見(jiàn)國(guó)家有關(guān)法律法規(guī),當(dāng)本聲明與國(guó)家法律法規(guī)沖突時(shí),以國(guó)家法律法規(guī)為準(zhǔn)。

4、如果侵害了您的合法權(quán)益,請(qǐng)您及時(shí)與我們,我們會(huì)在第一時(shí)間刪除相關(guān)內(nèi)容!

聯(lián)系方式:010-60259772
電子郵件:394588593@qq.com