`

21个常用的PHP函数代码段

    博客分类:
  • php
阅读更多
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=”";
013 srand ((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  
023 2. PHP生成一个随机字符串
024  
025 如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
026  
027 /*************
028 *@l – length of random string
029 */
030 function generate_rand($l){
031 $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
032 srand((double)microtime()*1000000);
033 for($i=0; $i<$l$i++) {
034 $rand.= $c[rand()%strlen($c)];
035 }
036 return $rand;
037 }
038  
039 3. 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  
063 4. 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 }
075 else
076 return true;
077 else
078 return false;
079 }
080  
081 5. 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  
102 6. 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 }
127 else
128 {
129 unlink($dir.$ds.$file);
130 }
131 }
132 closedir($handle);
133 rmdir($dir);
134 return true;
135 }
136 else
137 {
138 return false;
139 }
140 }
141  
142 7. 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  
151 8. PHP解析 XML 数据
152  
153 //xml string
154 $xml_string=”
155  
156  
157 Foo
158 foo@bar.com
159  
160  
161 Foobar
162 foobar@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  
180 9. PHP创建日志缩略名
181  
182 创建用户友好的日志缩略名。
183  
184 function create_slug($string){
185 $slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);
186 return $slug;
187 }
188  
189 10. 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 }
204 else
205 {
206 $ip=$_SERVER['REMOTE_ADDR'];
207 }
208 return $ip;
209 }
210  
211 11. 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));
222 header(‘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  
230 12. 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  
261 13. PHP寻找两个字符串的相似性
262  
263 PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。
264  
265 similar_text($string1$string2$percent);
266 //$percent will have the percentage of similarity
267  
268 14. 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  
284 15. 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  
306 16. 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 }
344 else
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  
353 17. 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  
373 18. PHP为 URL 地址预设 http 字符串
374  
375 有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。
376  
377 if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
378 $_POST['url'] = ‘http://’.$_POST['url'];
379 }
380  
381 19. 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  
396 20. 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  
438 21. 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 }
分享到:
评论

相关推荐

    php运行时间计算函数

    速度测试函数  为了优化代码,我们需要一种可以测试代码运行...现在可以轻松地检查任何一段代码的执行时间了,甚至我们可以同时使用多个计时器,只需在使用上述的几个函数时设定不同的参数作为计时器的名称就可以了。

    PHP代码:基本数据结构和php内置函数

    PHP代码:基本数据结构和php内置函数(1) //-------------------- // 基本数据结构 //-------------------- //二分查找(数组里查找某个元素) function bin_sch($array, $low, $high, $k){ if ($low $high){ $mid...

    21个PHP函数function.doc下载

    21个PHP函数function.doc下载 PHP 是目前使用最广泛的基于 Web 的编程语言,驱动着数以百万计的网站,其中也包括如 Facebook 等一些大型站点。这里收集了 21 段实用便捷的 PHP 代码摘录,对每种类型的 PHP 开发者...

    php中将session保存到数据库的函数类代码

    一段php中将session保存到数据库的函数类代码,可以使用session_set_save_handler()来注册连接数据的函数。

    luan-php-snippets:适用于Visual Studio CodePHP代码段包

    栾PHP代码段-Visual Studio代码扩展此扩展包括功能齐全的PSR兼容PHP代码段,可轻松快速地进行开发。 没有大的摘要! 没有取消保留的功能!特征片段描述php &lt;?php?&gt; po &lt;?php cls 类文件名class 类文件名...

    php中将session保存到数据库的函数类代码.zip

    分享一段php中将session保存到数据库的函数类代码,可以使用session_set_save_handler()来注册连接数据的函数。需要的朋友们可以下载参考。

    超实用的jQuery代码段

    超实用的jQuery代码段精选近350个jQuery代码段,涵盖页面开发中绝大多数要点、技巧与方法,堪称史上最实用的jQuery代码参考书,可以视为网页设计与网站建设人员的好帮手。《超实用的jQuery代码段》的代码跨平台、跨...

    PHP常用的小程序代码段

    本文实例讲述了PHP常用的小程序代码段。分享给大家供大家参考,具体如下: 1.计算两个时间的相差几天 $startdate=strtotime(2009-12-09); $enddate=strtotime(2009-12-05); 上面的php时间日期函数strtotime已经把...

    一段实用的php验证码函数

    代码段一:简单php验证码函数 &lt;?php function code(){ $im = imagecreatetruecolor(100, 40); $black = imagecolorallocate($im, 0, 0, 0); $white = imagecolorallocate($im, 255, 255, 255); imagefill($...

    php 实现一个字符串加密解密的函数实例代码

    php 实现一个字符串加密解密的函数 函数代码如下: /********************************************************************* 函数名称:encrypt 函数作用:加密解密字符串 使用方法: 加密 :encrypt('str','E','...

    PHP常见字符串操作函数与用法总结

    一、字符串的格式化 1、字符串的格式化 trim()函数可以去除字符串的开始位置和结束位置的空格,并将结果字符串返回,默认情况下去除的字符是换行符和回车符(\n和\r),水平和垂直制表符(\t和X0B) ltrim()函数只从...

    PHP零基础入门到原生项目开发【完整版】

    步骤2: PHP函数库 本阶段主要介绍自定义函数的定义和用法,字符串函数库、数学函数库、日期时间函数库三大系统函数库,同时详细介绍了什么是数组,数组如何定义以及如何使用 步骤3: PHP常用操作 本阶段主要带领大家...

    php使用file函数、fseek函数读取大文件效率对比分析

    php读取大文件可以使用file函数和fseek函数,但是二者之间效率可能存在差异,本文章向大家介绍php file函数与fseek函数实现大文件读取效率对比分析,...下面是一段用file来取出这具文件最后一行的代码: &lt;?php in

    PHP URL地址获取函数代码(端口等) 推荐

    PHP URL地址获取函数代码(端口等) ,看了这段代码,基本上其它的不用看了,直接拿来使用即可。

    收集的二十一个实用便利的PHP函数代码

    这里收集了 21 段实用便捷的 PHP 代码摘录,对每种类型的 PHP 开发者都会有所帮助。 1. PHP可阅读随机字符串 此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。 /*************...

    PHP高级对象构建 多个构造函数的使用

    下面就用一段代码示例来演示一下PHP高级对象构建中的使用多个构造函数进行对象构建的原理。 复制代码 代码如下: &lt;?php class classUtil {//这是一个参数处理的类 public static function typeof($var){ if (is_...

    PHP 正则表达式常用函数

    $matches[0]将包含与整个模式匹配的文本,$matches[1]将包含第一个捕获的与括号中的模式单元所匹配的内容,以此类推。该函数只 作一次匹配,最终返回0或1的匹配结果数。代码6.1给出preg_match()函数的一段代码示例。...

    PHP基础教程 是一个比较有价值的PHP新手教程!

    ASP只是一个一般的引擎,具有支持多种语言的能力,不过默认的并且是最常用的还是VBScript。 mod_perl与Perl一样强大,只是更快一些。 二、PHP入门 PHP站点的在线教程已经很棒了。在那里还有一些其他教程的链接。...

    php检测网页是否被百度收录的函数代码

    下面给出一段php函数,功能是检测一个网页是否被百度收录,直接给出代码

Global site tag (gtag.js) - Google Analytics