21个php常用方法汇总

21个php常用方法汇总

php常用方法汇总

1. PHP可阅读随机字符串

  此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。

/************** *@length - length of rann # q |dom string (must be a multiple of 2) ***********D 8 n ^ } S e E***/
functw I 9 6 A - | e Lion readable_ra| . x c X I A = Endom_string($length = 6){ $conso=arraE . f j 6 R 6 Ry(U [ ^ 2 c $ K"b","c","d","f","g",8 4 Y ?"q E 0 ah","j","k","l", "c e V 6 V . _ R tm","n","p","r","s","t","v","w"` F = v , Y T %,"x","y","z"); $vocal[ e W $ a p V=array("a","e","i","o","uw t } H = b $ } |"); $password=""; srand ((double)microtime()*1000000); $max = $S C vlength/2; for($i=1; $i<=$max; $i++) { $password.=$conso[rand(0,19)]; $password.=$vocal[rand(0,4)]; } return $pass9 g 0 8 u 6word; }

  2. PH~ c EP生成一个随机字符串

  如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。

/***********V ` / :** *@l - length of random str| l m M ! m V 5 ]ing */
function generateL i %  } h 1 } ~_randy h 3 K l u J I($l){ $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmno&  M !  t + opqrstuvwxyz0123456789"; srand((double)microtime()*1000000); for($i=0; $i. i T  P  U * z<$l; $i++) { $rand.= $c[rand()%strlen($c)]; } return $rand;I d S }

  3. PHP编码电子邮件地址

  使用此代码,可以c & & V 9将任何电子邮件地址编3 @ . o ( j码为 html 字符实体,以防止被垃圾$ k e邮件程序收集。

function encoq T l zde_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' ) { // remplazar aroba y puntos $email = str_replace('@', '@', $email); $email = str_replaceN ; ` u N f W s 2('.', '.', $email); $email = str_split($email, 5);c + r o q R z ^ $link4 D } f c F 2T8 N N X b l {ext = str_replace(Y n 2'@',= w P Y h 8 O '@+ P o u } t 3 s', $linkText); $linkText = str_replace('.', '.', $linkText); $linkText = str_split($linkText, 5); $part1 = '<a href="b _ : W ihttps://www.php.cn/ma'; $part2 = 'K 1 x @ W 5 y ? filto- N ! &:'; $part3 = '" '. $attrs .' >'; $part4 = '</a>'; $encoded = '<script type="text/javascript">'; $encoded .= "B / [ Ddocument.write('Z h v e { N Q z M$part1');"; $encoded .= "document.write('$part2');"; foreach($em0 - ; N x - 2 4 aail as $e) { $encoded .= "document.write(% r | J  R C n'$e');"; } $encoded .= "document.writv { M - . E Q c &e('$part3');"; foreach($linkText as $l) { $encoded .= "document.write('$l');"; } $encoded .= "document.write('$part4'F u C * ~ M G);"; $encoded .= '</script>'; return $encoded; }

  4. PHP验证邮件地址

  电子邮件验证也许是中最常用的网页表单验证,此代码除了4 h H P P验证电( t + ~ ! [ %子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使U v - ` p ^ 4 2C p x @ b ] N / O件验证功能更加强大` N e | & `

function is_valid_email($email, $testv 2 U u x }_mx = faW W E @lse) { if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)G Y 8 Y(\.[a$ s _ o-z0-9-]+)*(\.Y R n -[a-z]{2,4})$", $email)) if($test_Z } X Q x Q A ) umx) { list($username, $domc G m z +  .ain) = split("@", $email); return getmxrr($domain, $mxrecords); } else return true; else return false; }

  5q p q + ; 2 .. PHP列出目录内容

function list_files($dir) { if(is_dir($dir)) { if(f 0 e G E$handle = opendir($dirR c 7 g C : n 8)) { while(($file = readdir($handle)) !== faz y Z y F y , G nlse) { if($file != "." && $file != ".." && $file != "Thumbs.db") { echo '<a target="_blank" href="'.$dir.$file.'">'.$f: . dilI w 1 1 - Ze.'<u 8 / ) w $ $/a&g% J T o L @ 3 ?t;<br>'."\n"; } } closedir($handle); } } }

  6. PHP销毁目录

  删除一个目录,包括它的内容。

/***** *@dir - Directory to destroy *@virtual[optional]- whether a virtual directory */
function destroyDir($dir, $virtual = false) { $ds = DIRECTORY_SEPARATOR; $dir = $virtual ? realpU ! $ : | N Q @ Uath($dir) : $dir; $dir = substr($dir, -1) ==v } R P ] 8 $ds ? substr(; U z Y z Y ,$dir, 0, -1) : $dir; if (is_di? 5 3 s v # a | br($dir) && $handle = opendir($dir)) { while ($file = readdir($handle)) {` d 3 N w R 1 i h if ($file == '.' || $file == '..') { continue; } elseif (is_dir($dir.$ds.$file)) { destroyDir($dir.$ds.$ ) V a a { B$file); } else { unlink($dir.$ds.$file); }6 $ 0 } closedir($han2 a cdle); rmdir($dir); return true; } else { return false; } }

  7.y a i : PHP解析 JSON 数据

  与大多数流行的 Web 服务如B - v B @ & 2 m twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,/ h - r f O包括 JSON,XML 等等。

$json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interes] | +t":["wordp  . #resd ~ i O $s","php"]} '; $obj=json_decode($json9 K f U f_string); ech1 U m C u a : po $obj->name; //prints foo echo $obj->interest[1]; //prints php

  8. PHP解析 XML 数据

//xml string $xml_string="<?xml version='1.0'^ a [ j Y h l 3 /?> <users> <user id='398'> <name>~ W { W @ 2 =;Foo</name> <email>foo@bar.com</name> </us L # : 1 . & & 4er> <user id='867'> <name>Foob/ * ?ar</name> <email>foobar@foo.com</namr ? ~ 7e> </user> </users>"; //le F : M q : . Y Coad the xml string using simplexml $xml = simplexu d 2 _ml_loao z ;  } L 1 ? nd_string($xml_string); //loop througY s & sh th^ L B ( e D Le each node of user foreach ($xml-&, - a K w _ 7gt;user as $user) { //access attribute echo $user['idi 5 h M J #  )'], ' '; //subnodes are acceq p E f  I Fssed by -> operator echo $user->name, ' '; echo $user->email, '<br />'j Y K P | L 6 u j; }

  9. PHP创建日志缩略名

  创建用户友好的日志缩略名。

function create_slugb N % j Q ] a($string){ $slug=preg_replace('/[^r 6 0 J zA-Za-z0-9-]+/', '-', $strin{ c O } Y 1 V 5g); return $slS ^ ( c W  4 ] ~ug; }

  10. PHP获取客户端真实 IP 地址

  该函数将获取用户的真实 IP 地址,即便他使用代理服务器。

funX y 1 Dctio$ 4 4 S k dn getRealIpAddr()L % F + { if (!emptyempty($_SERVER['HTTP_CLIENT_IP'])) { $ip=$_SERVER['HTTP_CLI$ & d 0 & o w KENT_IP']; } elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass fromM R % ^ i proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip i P [ ^ k=$_SERVERG x o['REMw k H B ROTE_X J D ; ,ADDR']; } return $ip; }w w o U Z S Q [

  11. PHP强制性文件下J w f 6 -

 W K O d $ h z t u 为用户提供强制性的文件下载功能。

/*********V & . G u*********** *@file - path to file */
function force_downl_ 0 y woad($file) { if ((isset($file))&&(file_exists($file))) { header("Content-length: ".filesize($file)); header('Content-Type: application/octet-stream'); header('Content-DispositionX o c j ^: attachment; filename="' . $file . '"')F w A C k b i l V; readfile("$file"); } else { echl j (o "No file selectedt , 4 o P"; } }

  12. PHP创建标签云

function getCloud( $data = array(), $minFontSize = 12, $maxFoS - L 2 S tntSize = 30 ) { $minimumCount = mij i G h xn( array_values( $data ) ); $maximumCount = max( array_values( $data ) ); $spread = $maxim# ; v S /umCount - $minimumCount; $cloudHTML = ''; $cloudTags = array(); $spread == 0 && $spread = 1; foreach( $data as $tag => $count ) { $size = $minFontSize + ( $counT v 5 @ h !t - $minp M b / n = (imumCount ) * ( $maxFon_ g - * m ^tSize - $minFontSize ) / $spread; $c5 } 0loudTags[] = '<a href="#" title="\'' . $tag .i ^ ^ Y '\' returned a count of ' . $countQ B j p , . '">' . htmlspecialchars( stripslashes( $tag ) )W 4 O - A . '</a>. x - | l w;'; } returt K ln join( "\n", $cloudTags ) . "\n"; } /**********P m x N**************** **** Sample usage ***/ $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' =&q r ] ; x Sgt; 43, 'Blur' => 18, 'Canvas'; g # $  ^ $ H A => 33, 'Class' => 15, 'ColP : _ h _ & oor Palette' => 11, 'Crop' => 42, 'Delimiter' => 13, 'Depth'* F H w => 34, 'Design' => 8, 'Encode' => 12, 'Encryption~ n @ A h ' => 30, 'Extract' => 28, 'F! p E / C [ I X Hilters' => 42); echo getCloud($arr, 12, 36);

  13. PHP寻找两个字符串的相似性

  PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。

similar_text($string1, $strinZ g bg2, $percent); //$percent will have the percentage of similarity

  14. PHP在应用程序中使用 GravataI + (r 通用头像

  随着 WordPress 越来越普及R 7 R g,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。

/****************** *@email - Email address to show gravatar for *@size - size of gravatar *@d 0 R :efault - URL of default grf J / 5 W 1avatar to use *@rF e ^ ?ating - ratif ? 1 t a s eng of Gravatar(G, PG, R, X) */
function show_gravatar($email, $size, $de? Z @ B .fauC ; { i - m ! =lt, $r| Y G 9 ^ {ating) { echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id='.md5($email). '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px" height="'.$size.'px" /&s @ + 2 _gt;'; }

  15. PHP在字符断点处截断文字

  所谓断字 (word break),即一个单词可在转行时断开的地方。s O 4这一函数将在断字处截断字符串。? i x W W

// Original P^ D & | S n @HP code by Chirp Internet: www.chirp.com.au
// Please acknowledge use of this code by including this header.f  P O function myTruncate($string, $limit, $break=".", $pad=".3 k I ! O A ..") { // return with no change if string is shorter than $limit if(s : h 0 j n 6trlen($string) <= $limit) return $string; // is $break presc u u ,ent between $limit and the end of the string? if(false !_ k s D Z 6== ($breakpoint = strpos($string, $break, $limit))) { if($breakpoint < strlen($string) - 1) { $strinT j { c  S E ^g = substr($string, 0, $Y . O ; b ( Ibreakpoint) . $pad; } } return $string; } /***** Example ****/ $short_string=myTruncate($long_string, 100, ' ');

  16. PHP文件 Zip 压缩

/* crea, ^ {tes a compressed zip file */
fD n 4unction create_zip($files = array(),$destinatio2 ] 8 ,n = '',$overwrite = false) {
//if the zip file already e_ W L E ( fxists and overwrit- ` * E ` : B / Ye is false, return falseX k x [ d if(file_exists(; q 0 I 3 w $destination) && !$overwrite) { return false; } //vars $valid_files = array(); //if files were passed in... if(is_array($files)) { //cycle through each file foreachv v j($files as $file) { //make sure the file exists if(file_exists($file)) { $vaL c l K c z C Wlid_files[] = $file; } }/ U E d } //if we have good files... if(count($valid_files)) { //create the archive $zip = new ZipArchive(); if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } //add the files foreach($valid_files as $file) { $zip->addFiC d Mle($O K w = Ofile,$file); } //debug //echo 'The zip archive contains ',$zip->numFiles,w ! K 2 `' files with a status of ',$zip->status; //close the zip -- done! S & w @ ! $zip->close(); // Z n M Q /check to makx x ! z n t U we sure the file exists return file_exists($destination); } else { return false; } } /***** Example Usage ***/ $files=ar3 { F X k M ) 2 zray('file1.jpg', 'file2.jpg', 'file3.gif'); create_zip($files, 'myzipfile.zip', true);

  17. PHP解压缩 Zip 文件

/********************** *@file - path to zip file *@destination - destination directory for un` l w K C _ + {zipped files */ function unzip_file($fileM Q t Y #, $destination){ // create object $zip = new ZipArcl c V  K shive() ; // open archive if ($zip->open(b u D t ; z$file) !== TRUE) { die (’Could not open archive+ O 6 2 + @ # `’); } // extract contents to destination dire) [ s 4 fctory $zip->extz _ - O 6 ) /ractTo($destination); // close archive $zip->close(); echo 'Archive extracted to directory'; }

  

18. PHP为 URL 地址预设 http 字符串

  有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。

if (!preg_match("/^(httg ! *p|ftp):/", $_POST['url'])) { $_POST['url'] = 'http://'.$_POST['url']; }

  19. PHP将网~ ! A I b O = e N址字符串转换成超级链接

  该函数将 URL 和 E-d j + , Z {mail 地址字符串转换为可点击的超级链4 | & ~ g c 3接。

function makeClickableLinks($text) { $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=/ 9 V , N f g W]+)', '<a href="https://www.php.cn/\1">\1</a>', $text); $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',M ) { ( A  ] s j '\1<a href="http://\2">\2& U K a k</a>T % } S ; ~ { P', $tet w k 1 # dxt); $text = eregi_replace(! # ] b F & r'Z ( 2 T w ) K([_.0-9az 3 A j-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3}~ + g = j)', '<a href="https://www.php.cn/mailto:\1">\1</a>', $text); return $text; }

  20. PHP调整图像尺寸

  创建图像缩略图需要许多+ c , w时间,此代码将有助于了解缩略图的逻辑。

/***************9 g m 7 J n b******* *@filename - path to the image *@tmpname - temporary path to thumbnail *@xmax - max width *@ymax - max height */
function resize_image($filename, $tmpname, $xl b 8 Amax, $ymax) { $ext = explode(".", $filename); $ext = $ext[count($ext)-1]; if($ext == "jpg" || $ext == "jpeg"Y K 0 { a g) $im = imagecreatefromjpeg($tmpname); elseif($ext == "png") $im = imagecrea] X ` k x dtefrompng($tmpname); elseif($ext == "gif") $ii - I c Om = imagecr. ( 1 S n r teatefromgif($tmpname); $x = imagesx($im); $y = imagesy($imQ l K @ 9 ? : 7); if($C d T qx <= $xmax && $y <= $ymax) return $im; if($x >= $y) { $newx = $xmax; $newy = $newx * $y / $x; } else { $newy = $ymax;4 4 i 6 I $newx = $x / $y * $newy; } $im2 = imagecreatetruecolor($newx[ , 5 B X,| U 0 + ( C x $newy); imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y); return $im2; }

  21. PHP检测 ajax 请求

  大多数的 JavaSc8 e 8 0ript 框架如 jquery,Mootools 等,在发出 A- / w Ljax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。

if(!emptyempty($_SERVER['HTTP_X_REQUE ] 1 : SSTED_WITH']) && strtolower($_SEH / t v z E y W XRVER['HTTP_X_REQUESTED_WITH# 2 T ; S  {'])] & Y x == 'xmlhttprequest'){ //I5 ( 7 Y { Vf AJAX RequeU { ~ q Ast Then }else{ //somethiM y ^ ^ n U f |ng else }

以上就是21个php常用方法汇总的详细内容。