PHP 程式碼片段

來源:互聯網
上載者:User

標籤:log   round   palette   用戶端   proxy   ret   ima   檔案下載   wordpress   

轉載的, 用著方便!

1. 可閱讀隨機字串 此代碼將建立一個可閱讀的字串,使其更接近詞典中的單詞,實用且具有密碼驗證功能function readable_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;}2. 產生一個隨機字串如果不需要可閱讀的字串,使用此函數替代,即可建立一個隨機字串,作為使用者的隨機密碼等。function generate_rand($len){ $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; srand((double)microtime()*1000000); for($i=0; $i<$len; $i++) { $rand.= $c[rand()%strlen($c)]; } return $rand;} function rand_password( $length = 8 ) { // 密碼字元集,可任意添加你需要的字元 $chars = ‘[email protected]#$%^&*()-_ []{}<>~`+=,.;:/?|’; $password = ”; for ( $i = 0; $i < $length; $i++ ) { // 這裡提供兩種字元擷取方式 // 第一種是使用 substr 截取$chars中的任意一位字元; // 第二種是取字元數組 $chars 的任意元素 // $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1); $password .= $chars[ mt_rand(0, strlen($chars) - 1) ]; } return $password; } 3. 編碼電子郵件地址可以將任何電子郵件地址編碼為 HTML 字元實體,以防止被垃圾郵件程式收集。 function encode_email($email=‘[email protected]‘, $linkText=‘Contact Us‘, $attrs =‘class="emailencoder"‘ ) { // remplazar aroba y puntos $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 = ‘<a href="ma‘; $part2 = ‘ilto:‘; $part3 = ‘" ‘. $attrs .‘ >‘; $part4 = ‘</a>‘; $encoded = ‘<script type="text/javascript">‘; $encoded .= "document.write(‘$part1‘);"; $encoded .= "document.write(‘$part2‘);"; foreach($email as $e) { $encoded .= "document.write(‘$e‘);"; } $encoded .= "document.write(‘$part3‘);"; foreach($linkText as $l) { $encoded .= "document.write(‘$l‘);"; } $encoded .= "document.write(‘$part4‘);"; $encoded .= ‘</script>‘; return $encoded; } 4. 驗證郵件地址 此代碼除了驗證電子郵件地址,也可以選擇檢查郵件域所屬 DNS 中的 MX 記錄,使郵件驗證功能更加強大 function is_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); return getmxrr($domain, $mxrecords); } else return true; else return false; } 5. 列出目錄內容 function list_files($dir) { if(is_dir($dir)) { if($handle = opendir($dir)) { while(($file = readdir($handle)) !== false) { if($file != "." && $file != ".." && $file != "Thumbs.db") { echo ‘<a target="_blank" href="‘.$dir.$file.‘">‘.$file.‘</a><br>‘."\n"; } } closedir($handle); } } } ----------------------------- function list_dir($path){ $dp = dir($path); while( $fp = $dp->read() ){ if ( $fp==‘.‘ ){ } } } ----------------------------- 7. 解析 JSON 資料 $json_string=‘{"id":1,"name":"foo","email":"[email protected]","interest":["wordpress","php"]} ‘; $obj=json_decode($json_string); echo $obj->name; //prints foo echo $obj->interest[1]; //prints php $ary = json_decode($json_string,true); echo $ary[‘id‘]; 10. 擷取用戶端真實 IP 位址 function getRealIpAddr() { if (!emptyempty($_SERVER[‘HTTP_CLIENT_IP‘])) { $ip=$_SERVER[‘HTTP_CLIENT_IP‘]; } elseif (!emptyempty($_SERVER[‘HTTP_X_FORWARDED_FOR‘])) //to check ip is pass from proxy { $ip=$_SERVER[‘HTTP_X_FORWARDED_FOR‘]; } else { $ip=$_SERVER[‘REMOTE_ADDR‘]; } return $ip; } 11. 強制性檔案下載 function force_download($file){ if ((isset($file))&&(file_exists($file))) { header("Content-length: ".filesize($file)); header(‘Content-Type: application/octet-stream‘); header(‘Content-Disposition: attachment; filename="‘ . $file . ‘"‘); readfile("$file"); } else { echo "No file selected"; }}12. 建立標籤雲function getCloud($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($data as $tag => $count){ $size = $minFontSize + ($count - $minimumCount) * ($maxFontSize - $minFontSize) / $spread; $cloudTags[] = ‘<a style="font-size: ‘ . floor($size) . ‘px‘ . ‘" href="#" title="\‘‘ . $tag . ‘\‘ returned a count of ‘ . $count . ‘">‘ . htmlspecialchars(stripslashes($tag)) . ‘</a>‘; } return join("\n", $cloudTags) . "\n";}/** * Sample usage ** */$arr = Array(‘Actionscript‘ => 35, ‘Adobe‘ => 22, ‘Array‘ => 44, ‘Background‘ => 43, ‘Blur‘ => 18, ‘Canvas‘ => 33, ‘Class‘ => 15, ‘Color Palette‘ => 11, ‘Crop‘ => 42, ‘Delimiter‘ => 13, ‘Depth‘ => 34, ‘Design‘ => 8, ‘Encode‘ => 12, ‘Encryption‘ => 30, ‘Extract‘ => 28, ‘Filters‘ => 42);echo getCloud($arr, 12, 36);13. 尋找兩個字串的相似性similar_text(‘abcde‘, ‘abcdef‘, $percent);echo $percent;16. 檔案 Zip 壓縮function create_zip($files = array(), $destination = ‘‘, $overwrite = false){ if(file_exists($destination) && !$overwrite){ return false; } $valid_files = array(); if(is_array($files)){ foreach($files as $file){ if(file_exists($file)){ $valid_files[] = $file; } } } if(count($valid_files)){ $zip = new ZipArchive(); if($zip -> open($destination, $overwrite ? ZIPARCHIVE :: OVERWRITE : ZIPARCHIVE :: CREATE) !== true){ return false; } foreach($valid_files as $file){ $zip -> addFile($file, $file); } $zip -> close(); return file_exists($destination); }else{ return false; }}/** * **** Example Usage ** */$files = array(‘question_20120828_211308.csv‘, ‘question_20120828_211326.csv‘);create_zip($files, ‘myzipfile.zip‘, true);17. 解壓縮 Zip 檔案function unzip_file($file, $destination){ $zip = new ZipArchive() ; if ($zip->open($file) !== TRUE) { die (‘Could not open archive‘); } $zip->extractTo($destination); $zip->close();}20. 調整映像尺寸$imgsrc = "http://www.nowamagic.net/images/3.jpg";$width = 780;$height = 420;resizejpg($imgsrc, $imgdst, $width, $height);function resizejpg($imgsrc, $imgdst, $imgwidth, $imgheight){ // $imgsrc jpg格式映像路徑 $imgdst jpg格式映像儲存檔案名稱 $imgwidth要改變的寬度 $imgheight要改變的高度 // 取得圖片的寬度,高度值 $arr = getimagesize($imgsrc); header("Content-type: image/jpg"); $imgWidth = $imgwidth; $imgHeight = $imgheight; // Create image and define colors $imgsrc = imagecreatefromjpeg($imgsrc); $image = imagecreatetruecolor($imgWidth, $imgHeight); //建立一個彩色的底圖 imagecopyresampled($image, $imgsrc, 0, 0, 0, 0, $imgWidth, $imgHeight, $arr[0], $arr[1]); imagepng($image); imagedestroy($image);}21. 數組轉 json 格式, 包含中文字元 替代json_encodefunction jsonEncode($var) { switch (gettype($var)) { case ‘boolean‘: return $var ? ‘true‘ : ‘false‘; case ‘integer‘: case ‘double‘: return $var; case ‘resource‘: case ‘string‘: return ‘"‘. str_replace(array("\r", "\n", "<", ">", "&"), array(‘\r‘, ‘\n‘, ‘\x3c‘, ‘\x3e‘, ‘\x26‘), addslashes($var)) .‘"‘; case ‘array‘: if (empty($var) || array_keys($var) === range(0, sizeof($var) - 1)) { $output = array(); foreach ($var as $v) { $output[] = jsonEncode($v); } return ‘[ ‘. implode(‘, ‘, $output) .‘ ]‘; } case ‘object‘: $output = array(); foreach ($var as $k => $v) { $output[] = jsonEncode(strval($k)) .‘: ‘. jsonEncode($v); } return ‘{ ‘. implode(‘, ‘, $output) .‘ }‘; default: return ‘null‘; } }22. 刪除目錄及其下所有檔案//Delete folder functionfunction deleteDirectory($dir) { if (!file_exists($dir)) return true; if (!is_dir($dir) || is_link($dir)) return unlink($dir); foreach (scandir($dir) as $item) { if ($item == ‘.‘ || $item == ‘..‘) continue; if (!deleteDirectory($dir . "/" . $item)) { chmod($dir . "/" . $item, 0777); if (!deleteDirectory($dir . "/" . $item)) return false; }; } return rmdir($dir);}

  

PHP 程式碼片段

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.