21个常用的PHP函数代码段

本文汇集了PHP编程中常用的代码片段,涵盖了从生成可读随机字符串、创建标签云、文件操作到邮件地址处理等多个方面,为开发者提供了便捷的工具集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. PHP可阅读随机字符串
002 
003此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。
004 
005/**************
006*@length – length of random string (must be a multiple of 2)
007**************/
008 function readable_random_string($length = 6){
009 $conso=array(“b”,”c”,”d”,”f”,”g”,”h”,”j”,”k”,”l”,
010“m”,”n”,”p”,”r”,”s”,”t”,”v”,”w”,”x”,”y”,”z”);
011 $vocal=array(“a”,”e”,”i”,”o”,”u”);
012 $password=”";
013srand ((double)microtime()*1000000);
014 $max $length/2;
015 for($i=1; $i<=$max$i++)
016{
017 $password.=$conso[rand(0,19)];
018 $password.=$vocal[rand(0,4)];
019}
020 return $password;
021}
022 
0232. PHP生成一个随机字符串
024 
025如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
026 
027/*************
028*@l – length of random string
029*/
030 function generate_rand($l){
031 $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
032srand((double)microtime()*1000000);
033 for($i=0; $i<$l$i++) {
034 $rand.= $c[rand()%strlen($c)];
035}
036 return $rand;
037}
038 
0393. PHP编码电子邮件地址
040 
041使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。
042 
043 function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, $attrs=’class=”emailencoder”‘ )
044{
045// remplazar aroba y puntos
046 $email str_replace(‘@’, ‘&#64;’, $email);
047 $email str_replace(‘.’, ‘&#46;’, $email);
048 $email str_split($email, 5);
049 
050 $linkText str_replace(‘@’, ‘&#64;’, $linkText);
051 $linkText str_replace(‘.’, ‘&#46;’, $linkText);
052 $linkText str_split($linkText, 5);
053 
054 $part1 = ‘$part2 = ‘ilto&#58;’;
055 $part3 = ‘” ‘. $attrs .’ >’;
056 $part4 = ‘’;
057 
058 $encoded = ‘’;
059 
060 return $encoded;
061}
062 
0634. PHP验证邮件地址
064 
065电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。
066 
067 function is_valid_email($email$test_mx = false)
068{
069 if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))
070 if($test_mx)
071{
072 list($username$domain) = split(“@”, $email);
073 return getmxrr($domain$mxrecords);
074}
075else
076 return true;
077else
078 return false;
079}
080 
0815. PHP列出目录内容
082 
083 function list_files($dir)
084{
085 if(is_dir($dir))
086{
087 if($handle = opendir($dir))
088{
089 while(($file = readdir($handle)) !== false)
090{
091 if($file != “.” && $file != “..” && $file != “Thumbs.db”)
092{
093 echo ‘’.$file.’
094’.”\n”;
095}
096}
097 closedir($handle);
098}
099}
100}
101 
1026. PHP销毁目录
103 
104删除一个目录,包括它的内容。
105 
106/*****
107*@dir – Directory to destroy
108*@virtual[optional]- whether a virtual directory
109*/
110 function destroyDir($dir$virtual = false)
111{
112 $ds = DIRECTORY_SEPARATOR;
113 $dir $virtual realpath($dir) : $dir;
114 $dir substr($dir, -1) == $ds substr($dir, 0, -1) : $dir;
115 if (is_dir($dir) && $handle = opendir($dir))
116{
117 while ($file = readdir($handle))
118{
119 if ($file == ‘.’ || $file == ‘..’)
120{
121 continue;
122}
123 elseif (is_dir($dir.$ds.$file))
124{
125 destroyDir($dir.$ds.$file);
126}
127else
128{
129 unlink($dir.$ds.$file);
130}
131}
132 closedir($handle);
133 rmdir($dir);
134 return true;
135}
136else
137{
138 return false;
139}
140}
141 
1427. PHP解析 JSON 数据
143 
144与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。
145 
146 $json_string=’{“id”:1,”name”:”foo”,”email”:”foo@foobar.com”,”interest”:["wordpress","php"]} ‘;
147 $obj=json_decode($json_string);
148 echo $obj->name; //prints foo
149 echo $obj->interest[1]; //prints php
150 
1518. PHP解析 XML 数据
152 
153//xml string
154 $xml_string=”
155 
156 
157Foo
158foo@bar.com
159 
160 
161Foobar
162foobar@foo.com
163 
164”;
165 
166//load the xml string using simplexml
167 $xml = simplexml_load_string($xml_string);
168 
169//loop through the each node of user
170 foreach ($xml->user as $user)
171{
172//access attribute
173 echo $user['id'], ‘  ‘;
174//subnodes are accessed by -> operator
175 echo $user->name, ‘  ‘;
176 echo $user->email, ‘
177’;
178}
179 
1809. PHP创建日志缩略名
181 
182创建用户友好的日志缩略名。
183 
184 function create_slug($string){
185 $slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);
186 return $slug;
187}
188 
18910. PHP获取客户端真实 IP 地址
190 
191该函数将获取用户的真实 IP 地址,即便他使用代理服务器。
192 
193 function getRealIpAddr()
194{
195 if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
196{
197 $ip=$_SERVER['HTTP_CLIENT_IP'];
198}
199 elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
200//to check ip is pass from proxy
201{
202 $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
203}
204else
205{
206 $ip=$_SERVER['REMOTE_ADDR'];
207}
208 return $ip;
209}
210 
21111. PHP强制性文件下载
212 
213为用户提供强制性的文件下载功能。
214 
215/********************
216*@file – path to file
217*/
218 function force_download($file)
219{
220 if ((isset($file))&&(file_exists($file))) {
221 header(“Content-length: “.filesize($file));
222header(‘Content-Type: application/octet-stream’);
223 header(‘Content-Disposition: attachment; filename=”‘ . $file . ‘”‘);
224 readfile(“$file”);
225 else {
226 echo “No file selected”;
227}
228}
229 
23012. PHP创建标签云
231 
232 function getCloud( $data array(), $minFontSize = 12, $maxFontSize = 30 )
233{
234 $minimumCount = min( array_values$data ) );
235 $maximumCount = max( array_values$data ) );
236 $spread       $maximumCount – $minimumCount;
237 $cloudHTML    = ”;
238 $cloudTags    array();
239 
240 $spread == 0 && $spread = 1;
241 
242 foreach$data as $tag => $count )
243{
244 $size $minFontSize + ( $count – $minimumCount )
245 * ( $maxFontSize – $minFontSize ) / $spread;
246 $cloudTags[] = ‘. ‘” href=”#” title=”\” . $tag  .
247 ‘\’ returned a count of ‘ . $count . ‘”>’
248 . htmlspecialchars( stripslashes$tag ) ) . ‘’;
249}
250 
251 return join( “\n”, $cloudTags ) . “\n”;
252}
253/**************************
254****   Sample usage    ***/
255 $arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44, ‘Background’ => 43,
256‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11, ‘Crop’ => 42,
257‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12, ‘Encryption’ => 30,
258‘Extract’ => 28, ‘Filters’ => 42);
259 echo getCloud($arr, 12, 36);
260 
26113. PHP寻找两个字符串的相似性
262 
263PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。
264 
265 similar_text($string1$string2$percent);
266//$percent will have the percentage of similarity
267 
26814. PHP在应用程序中使用 Gravatar 通用头像
269 
270随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。
271 
272/******************
273*@email – Email address to show gravatar for
274*@size – size of gravatar
275*@default – URL of default gravatar to use
276*@rating – rating of Gravatar(G, PG, R, X)
277*/
278 function show_gravatar($email$size$default$rating)
279{
280 echo ‘‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”
281 height=”‘.$size.’px” />’;
282}
283 
28415. PHP在字符断点处截断文字
285 
286 所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。
287 
288// Original PHP code by Chirp Internet: www.chirp.com.au
289// Please acknowledge use of this code by including this header.
290 function myTruncate($string$limit$break=”.”, $pad=”…”) {
291// return with no change if string is shorter than $limit
292 if(strlen($string) <= $limit)
293 return $string;
294 
295// is $break present between $limit and the end of the string?
296 if(false !== ($breakpoint strpos($string$break$limit))) {
297 if($breakpoint strlen($string) – 1) {
298 $string substr($string, 0, $breakpoint) . $pad;
299}
300}
301 return $string;
302}
303/***** Example ****/
304 $short_string=myTruncate($long_string, 100, ‘ ‘);
305 
30616. PHP文件 Zip 压缩
307 
308/* creates a compressed zip file */
309 function create_zip($files array(),$destination = ”,$overwrite = false) {
310//if the zip file already exists and overwrite is false, return false
311 if(file_exists($destination) && !$overwrite) { return false; }
312//vars
313 $valid_files array();
314//if files were passed in…
315 if(is_array($files)) {
316//cycle through each file
317 foreach($files as $file) {
318//make sure the file exists
319 if(file_exists($file)) {
320 $valid_files[] = $file;
321}
322}
323}
324//if we have good files…
325 if(count($valid_files)) {
326//create the archive
327 $zip new ZipArchive();
328 if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
329 return false;
330}
331//add the files
332 foreach($valid_files as $file) {
333 $zip->addFile($file,$file);
334}
335//debug
336//echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
337 
338//close the zip — done!
339 $zip->close();
340 
341//check to make sure the file exists
342 return file_exists($destination);
343}
344else
345{
346 return false;
347}
348}
349/***** Example Usage ***/
350 $files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);
351 create_zip($files, ‘myzipfile.zip’, true);
352 
35317. PHP解压缩 Zip 文件
354 
355/**********************
356*@file – path to zip file
357*@destination – destination directory for unzipped files
358*/
359 function unzip_file($file$destination){
360// create object
361 $zip new ZipArchive() ;
362// open archive
363 if ($zip->open($file) !== TRUE) {
364 die (’Could not open archive’);
365}
366// extract contents to destination directory
367 $zip->extractTo($destination);
368// close archive
369 $zip->close();
370 echo ‘Archive extracted to directory’;
371}
372 
37318. PHP为 URL 地址预设 http 字符串
374 
375 有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。
376 
377 if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
378 $_POST['url'] = ‘http://’.$_POST['url'];
379}
380 
38119. PHP将网址字符串转换成超级链接
382 
383该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。
384 
385 function makeClickableLinks($text) {
386 $text eregi_replace(‘(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
387 ‘\1’, $text);
388 $text eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
389 ‘\1\2’, $text);
390 $text eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
391 ‘\1’, $text);
392 
393 return $text;
394}
395 
39620. PHP调整图像尺寸
397 
398创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。
399 
400/**********************
401*@filename – path to the image
402*@tmpname – temporary path to thumbnail
403*@xmax – max width
404*@ymax – max height
405*/
406 function resize_image($filename$tmpname$xmax$ymax)
407{
408 $ext explode(“.”, $filename);
409 $ext $ext[count($ext)-1];
410 
411 if($ext == “jpg” || $ext == “jpeg”)
412 $im = imagecreatefromjpeg($tmpname);
413 elseif($ext == “png”)
414 $im = imagecreatefrompng($tmpname);
415 elseif($ext == “gif”)
416 $im = imagecreatefromgif($tmpname);
417 
418 $x = imagesx($im);
419 $y = imagesy($im);
420 
421 if($x <= $xmax && $y <= $ymax)
422 return $im;
423 
424 if($x >= $y) {
425 $newx $xmax;
426 $newy $newx $y $x;
427}
428 else {
429 $newy $ymax;
430 $newx $x $y $newy;
431}
432 
433 $im2 = imagecreatetruecolor($newx$newy);
434 imagecopyresized($im2$im, 0, 0, 0, 0, floor($newx), floor($newy), $x$y);
435 return $im2;
436}
437 
43821. PHP检测 ajax 请求
439 
440大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。
441 
442 if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) &&strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){
443//If AJAX Request Then
444 }else{
445//something else
446}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值