转载的, 用着方便! 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_encode function 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 function function 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); }
时间: 2024-10-26 20:15:27