0

0

再来二十一段救命的PHP代码

php中文网

php中文网

发布时间:2016-06-21 08:53:00

|

1035人浏览过

|

来源于php中文网

原创

   1. php可阅读随机字符串

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

  1. /**************
  2. *@length - length of random string (must be a multiple of 2)
  3. **************/
  4. function readable_random_string($length = 6){
  5. $conso=array("b","c","d","f","g","h","j","k","l",
  6. "m","n","p","r","s","t","v","w","x","y","z");
  7. $vocal=array("a","e","i","o","u");
  8. $password="";
  9. srand ((double)microtime()*1000000);
  10. $max = $length/2;
  11. for($i=1; $i<=$max; $i++)
  12. {
  13. $password.=$conso[rand(0,19)];
  14. $password.=$vocal[rand(0,4)];
  15. }
  16. return $password;
  17. }

  2. PHP生成一个随机字符串

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

  1. /*************
  2. *@l - length of random string
  3. */
  4. function generate_rand($l){
  5. $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  6. srand((double)microtime()*1000000);
  7. for($i=0; $i<$l; $i++) {
  8. $rand.= $c[rand()%strlen($c)];
  9. }
  10. return $rand;
  11. }

  3. PHP编码电子邮件地址

立即学习PHP免费学习笔记(深入)”;

  使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。

  1. function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class="emailencoder"' )
  2. {
  3. // remplazar aroba y puntos
  4. $email = str_replace('@', '@', $email);
  5. $email = str_replace('.', '.', $email);
  6. $email = str_split($email, 5);
  7. $linkText = str_replace('@', '@', $linkText);
  8. $linkText = str_replace('.', '.', $linkText);
  9. $linkText = str_split($linkText, 5);
  10. $part1 = ' $part2 = 'ilto:';
  11. $part3 = '" '. $attrs .' >';
  12. $part4 = '';
  13. $encoded = '';
  14. return $encoded;
  15. }

  4. PHP验证邮件地址

  电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。

  1. function is_valid_email($email, $test_mx = false)
  2. {
  3. if(eregi("^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$", $email))
  4. if($test_mx)
  5. {
  6. list($username, $domain) = split("@", $email);
  7. return getmxrr($domain, $mxrecords);
  8. }
  9. else
  10. return true;
  11. else
  12. return false;
  13. }

  5. PHP列出目录内容

  1. function list_files($dir)
  2. {
  3. if(is_dir($dir))
  4. {
  5. if($handle = opendir($dir))
  6. {
  7. while(($file = readdir($handle)) !== false)
  8. {
  9. if($file != "." && $file != ".." && $file != "Thumbs.db")
  10. {
  11. echo '$dir.$file.'">'.$file.'
    '
    ."\n";
  12. }
  13. }
  14. closedir($handle);
  15. }
  16. }
  17. }

  6. PHP销毁目录

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

  1. /*****
  2. *@dir - Directory to destroy
  3. *@virtual[optional]- whether a virtual directory
  4. */
  5. function destroyDir($dir, $virtual = false)
  6. {
  7. $ds = DIRECTORY_SEPARATOR;
  8. $dir = $virtual ? realpath($dir) : $dir;
  9. $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
  10. if (is_dir($dir) && $handle = opendir($dir))
  11. {
  12. while ($file = readdir($handle))
  13. {
  14. if ($file == '.' $file == '..')
  15. {
  16. continue;
  17. }
  18. elseif (is_dir($dir.$ds.$file))
  19. {
  20. destroyDir($dir.$ds.$file);
  21. }
  22. else
  23. {
  24. unlink($dir.$ds.$file);
  25. }
  26. }
  27. closedir($handle);
  28. rmdir($dir);
  29. return true;
  30. }
  31. else
  32. {
  33. return false;
  34. }
  35. }

  7. PHP解析 JSON 数据

  与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。

  1. $json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
  2. $obj=json_decode($json_string);
  3. echo $obj->name; //prints foo
  4. echo $obj->interest[1]; //prints php

  8. PHP解析 XML 数据

  1. //xml string
  2. $xml_string="'1.0'?>
  3. '398'>
  4. Foo
  5. foo@bar.com
  6. '867'>
  7. Foobar
  8. foobar@foo.com
  9. ";
  10. //load the xml string using simplexml
  11. $xml = simplexml_load_string($xml_string);
  12. //loop through the each node of user
  13. foreach ($xml->user as $user)
  14. {
  15. //access attribute
  16. echo $user['id'], ' ';
  17. //subnodes are accessed by -> operator
  18. echo $user->name, ' ';
  19. echo $user->email, '
    '
    ;
  20. }

  9. PHP创建日志缩略名

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

  1. function create_slug($string){
  2. $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
  3. return $slug;
  4. }

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

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

  1. function getRealIpAddr()
  2. {
  3. if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
  4. {
  5. $ip=$_SERVER['HTTP_CLIENT_IP'];
  6. }
  7. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
  8. //to check ip is pass from proxy
  9. {
  10. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  11. }
  12. else
  13. {
  14. $ip=$_SERVER['REMOTE_ADDR'];
  15. }
  16. return $ip;
  17. }

  11. PHP强制性文件下载

ChatMind
ChatMind

ChatMind是一款AI生成思维导图的效率工具,可以通过AI对话生成和编辑思维导图。

下载

  为用户提供强制性的文件下载功能。

  1. /********************
  2. *@file - path to file
  3. */
  4. function force_download($file)
  5. {
  6. if ((isset($file))&&(file_exists($file))) {
  7. header("Content-length: ".filesize($file));
  8. header('Content-Type: application/octet-stream');
  9. header('Content-Disposition: attachment; filename="' . $file . '"');
  10. readfile("$file");
  11. } else {
  12. echo "No file selected";
  13. }
  14. }

  12. PHP创建标签云

  1. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
  2. {
  3. $minimumCount = min( array_values( $data ) );
  4. $maximumCount = max( array_values( $data ) );
  5. $spread = $maximumCount - $minimumCount;
  6. $cloudHTML = '';
  7. $cloudTags = array();
  8. $spread == 0 && $spread = 1;
  9. foreach( $data as $tag => $count )
  10. {
  11. $size = $minFontSize + ( $count - $minimumCount )
  12. * ( $maxFontSize - $minFontSize ) / $spread;
  13. $cloudTags[] = 'floor( $size ) . 'px'
  14. . '" href="#" title="\'' . $tag .
  15. '\' returned a count of ' . $count . '">'
  16. . htmlspecialchars( stripslashes( $tag ) ) . '';
  17. }
  18. return join( "\n", $cloudTags ) . "\n";
  19. }
  20. /**************************
  21. **** Sample usage ***/
  22. $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,
  23. 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42,
  24. 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30,
  25. 'Extract' => 28, 'Filters' => 42);
  26. echo getCloud($arr, 12, 36);

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

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

  1. similar_text($string1, $string2, $percent);
  2. //$percent will have the percentage of similarity

  14. PHP在应用程序中使用 Gravatar 通用头像

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

  1. /******************
  2. *@email - Email address to show gravatar for
  3. *@size - size of gravatar
  4. *@default - URL of default gravatar to use
  5. *@rating - rating of Gravatar(G, PG, R, X)
  6. */
  7. function show_gravatar($email, $size, $default, $rating)
  8. {
  9. echo '.md5($email).
  10. '&default='.$default.'&size='.$size.'&rating='.$rating.'" width="'.$size.'px"
  11. height="'.$size.'px" />';
  12. }

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

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

  1. // Original PHP code by Chirp Internet: www.chirp.com.au
  2. // Please acknowledge use of this code by including this header.
  3. function myTruncate($string, $limit, $break=".", $pad="...") {
  4. // return with no change if string is shorter than $limit
  5. if(strlen($string) <= $limit)
  6. return $string;
  7. // is $break present between $limit and the end of the string?
  8. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  9. if($breakpoint < strlen($string) - 1) {
  10. $string = substr($string, 0, $breakpoint) . $pad;
  11. }
  12. }
  13. return $string;
  14. }
  15. /***** Example ****/
  16. $short_string=myTruncate($long_string, 100, ' ');

  16. PHP文件 Zip 压缩

  1. /* creates a compressed zip file */
  2. function create_zip($files = array(),$destination = '',$overwrite = false) {
  3. //if the zip file already exists and overwrite is false, return false
  4. if(file_exists($destination) && !$overwrite) { return false; }
  5. //vars
  6. $valid_files = array();
  7. //if files were passed in...
  8. if(is_array($files)) {
  9. //cycle through each file
  10. foreach($files as $file) {
  11. //make sure the file exists
  12. if(file_exists($file)) {
  13. $valid_files[] = $file;
  14. }
  15. }
  16. }
  17. //if we have good files...
  18. if(count($valid_files)) {
  19. //create the archive
  20. $zip = new ZipArchive();
  21. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  22. return false;
  23. }
  24. //add the files
  25. foreach($valid_files as $file) {
  26. $zip->addFile($file,$file);
  27. }
  28. //debug
  29. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  30. //close the zip -- done!
  31. $zip->close();
  32. //check to make sure the file exists
  33. return file_exists($destination);
  34. }
  35. else
  36. {
  37. return false;
  38. }
  39. }
  40. /***** Example Usage ***/
  41. $files=array('file1.jpg', 'file2.jpg', 'file3.gif');
  42. create_zip($files, 'myzipfile.zip', true);

  17. PHP解压缩 Zip 文件

  1. /**********************
  2. *@file - path to zip file
  3. *@destination - destination directory for unzipped files
  4. */
  5. function unzip_file($file, $destination){
  6. // create object
  7. $zip = new ZipArchive() ;
  8. // open archive
  9. if ($zip->open($file) !== TRUE) {
  10. die (’Could not open archive’);
  11. }
  12. // extract contents to destination directory
  13. $zip->extractTo($destination);
  14. // close archive
  15. $zip->close();
  16. echo 'Archive extracted to directory';
  17. }

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

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

  1. if (!preg_match("/^(httpftp):/", $_POST['url'])) {
  2. $_POST['url'] = 'http://'.$_POST['url'];
  3. }

  19. PHP将网址字符串转换成超级链接

  该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。

  1. function makeClickableLinks($text) {
  2. $text = eregi_replace('(((fht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  3. '\1', $text);
  4. $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)',
  5. '\1\2', $text);
  6. $text = eregi_replace('([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})',
  7. '\1', $text);
  8. return $text;
  9. }

  20. PHP调整图像尺寸

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

  1. /**********************
  2. *@filename - path to the image
  3. *@tmpname - temporary path to thumbnail
  4. *@xmax - max width
  5. *@ymax - max height
  6. */
  7. function resize_image($filename, $tmpname, $xmax, $ymax)
  8. {
  9. $ext = explode(".", $filename);
  10. $ext = $ext[count($ext)-1];
  11. if($ext == "jpg" $ext == "jpeg")
  12. $im = imagecreatefromjpeg($tmpname);
  13. elseif($ext == "png")
  14. $im = imagecreatefrompng($tmpname);
  15. elseif($ext == "gif")
  16. $im = imagecreatefromgif($tmpname);
  17. $x = imagesx($im);
  18. $y = imagesy($im);
  19. if($x <= $xmax && $y <= $ymax)
  20. return $im;
  21. if($x >= $y) {
  22. $newx = $xmax;
  23. $newy = $newx * $y / $x;
  24. }
  25. else {
  26. $newy = $ymax;
  27. $newx = $x / $y * $newy;
  28. }
  29. $im2 = imagecreatetruecolor($newx, $newy);
  30. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
  31. return $im2;
  32. }

  21. PHP检测 ajax 请求

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

  1. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  2. //If AJAX Request Then
  3. }else{
  4. //something else
  5. }



PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
Golang处理数据库错误教程合集
Golang处理数据库错误教程合集

本专题整合了Golang数据库错误处理方法、技巧、管理策略相关内容,阅读专题下面的文章了解更多详细内容。

130

2026.02.06

java多线程方法汇总
java多线程方法汇总

本专题整合了java多线程面试题、实现函数、执行并发相关内容,阅读专题下面的文章了解更多详细内容。

50

2026.02.06

1688阿里巴巴货源平台入口与批发采购指南
1688阿里巴巴货源平台入口与批发采购指南

本专题整理了1688阿里巴巴批发进货平台的最新入口地址与在线采购指南,帮助用户快速找到官方网站入口,了解如何进行批发采购、货源选择以及厂家直销等功能,提升采购效率与平台使用体验。

736

2026.02.06

快手网页版入口与电脑端使用指南 快手官方短视频观看入口
快手网页版入口与电脑端使用指南 快手官方短视频观看入口

本专题汇总了快手网页版的最新入口地址和电脑版使用方法,详细提供快手官网直接访问链接、网页端操作教程,以及如何无需下载安装直接观看短视频的方式,帮助用户轻松浏览和观看快手短视频内容。

420

2026.02.06

C# 多线程与异步编程
C# 多线程与异步编程

本专题深入讲解 C# 中多线程与异步编程的核心概念与实战技巧,包括线程池管理、Task 类的使用、async/await 异步编程模式、并发控制与线程同步、死锁与竞态条件的解决方案。通过实际项目,帮助开发者掌握 如何在 C# 中构建高并发、低延迟的异步系统,提升应用性能和响应速度。

48

2026.02.06

Python 微服务架构与 FastAPI 框架
Python 微服务架构与 FastAPI 框架

本专题系统讲解 Python 微服务架构设计与 FastAPI 框架应用,涵盖 FastAPI 的快速开发、路由与依赖注入、数据模型验证、API 文档自动生成、OAuth2 与 JWT 身份验证、异步支持、部署与扩展等。通过实际案例,帮助学习者掌握 使用 FastAPI 构建高效、可扩展的微服务应用,提高服务响应速度与系统可维护性。

51

2026.02.06

JavaScript 异步编程与事件驱动架构
JavaScript 异步编程与事件驱动架构

本专题深入讲解 JavaScript 异步编程与事件驱动架构,涵盖 Promise、async/await、事件循环机制、回调函数、任务队列与微任务队列、以及如何设计高效的异步应用架构。通过多个实际示例,帮助开发者掌握 如何处理复杂异步操作,并利用事件驱动设计模式构建高效、响应式应用。

37

2026.02.06

java连接字符串方法汇总
java连接字符串方法汇总

本专题整合了java连接字符串教程合集,阅读专题下面的文章了解更多详细操作。

91

2026.02.05

java中fail含义
java中fail含义

本专题整合了java中fail的含义、作用相关内容,阅读专题下面的文章了解更多详细内容。

38

2026.02.05

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Excel 教程
Excel 教程

共162课时 | 16.4万人学习

Pandas 教程
Pandas 教程

共15课时 | 1万人学习

C# 教程
C# 教程

共94课时 | 9万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号