搜索
首页后端开发php教程给大家分享21个常用的PHP函数代码段

分享21个常用的PHP函数代码段
  1. 1. PHP可阅读随机字符串
  2. 此代码将创建一个可阅读的字符串,使其更接近词典中的单词,实用且具有密码验证功能。
  3. /**************
  4. *@length – length of random string (must be a multiple of 2)
  5. **************/
  6. function readable_random_string($length = 6){
  7. $conso=array(“b”,”c”,”d”,”f”,”g”,”h”,”j”,”k”,”l”,
  8. “m”,”n”,”p”,”r”,”s”,”t”,”v”,”w”,”x”,”y”,”z”);
  9. $vocal=array(“a”,”e”,”i”,”o”,”u”);
  10. $password=”";
  11. srand ((double)microtime()*1000000);
  12. $max = $length/2;
  13. for($i=1; $i{
  14. $password.=$conso[rand(0,19)];
  15. $password.=$vocal[rand(0,4)];
  16. }
  17. return $password;
  18. }
  19. 2. PHP生成一个随机字符串
  20. 如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
  21. /*************
  22. *@l – length of random string
  23. */
  24. function generate_rand($l){
  25. $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
  26. srand((double)microtime()*1000000);
  27. for($i=0; $i$rand.= $c[rand()%strlen($c)];
  28. }
  29. return $rand;
  30. }
  31. 3. PHP编码电子邮件地址
  32. 使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。
  33. function encode_email($email=’info@domain.com’, $linkText=’Contact Us’, $attrs =’class=”emailencoder”‘ )
  34. {
  35. // remplazar aroba y puntos
  36. $email = str_replace(‘@’, ‘@’, $email);
  37. $email = str_replace(‘.’, ‘.’, $email);
  38. $email = str_split($email, 5);
  39. $linkText = str_replace(‘@’, ‘@’, $linkText);
  40. $linkText = str_replace(‘.’, ‘.’, $linkText);
  41. $linkText = str_split($linkText, 5);
  42. $part1 = ‘$part2 = ‘ilto:’;
  43. $part3 = ‘” ‘. $attrs .’ >’;
  44. $part4 = ‘’;
  45. $encoded = ‘’;
  46. return $encoded;
  47. }
  48. 4. PHP验证邮件地址
  49. 电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。
  50. function is_valid_email($email, $test_mx = false)
  51. {
  52. if(eregi(“^([_a-z0-9-]+)(\.[_a-z0-9-]+)*@([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$”, $email))
  53. if($test_mx)
  54. {
  55. list($username, $domain) = split(“@”, $email);
  56. return getmxrr($domain, $mxrecords);
  57. }
  58. else
  59. return true;
  60. else
  61. return false;
  62. }
  63. 5. PHP列出目录内容
  64. function list_files($dir)
  65. {
  66. if(is_dir($dir))
  67. {
  68. if($handle = opendir($dir))
  69. {
  70. while(($file = readdir($handle)) !== false)
  71. {
  72. if($file != “.” && $file != “..” && $file != “Thumbs.db”)
  73. {
  74. echo ‘’.$file.’
  75. ’.”\n”;
  76. }
  77. }
  78. closedir($handle);
  79. }
  80. }
  81. }
  82. 6. PHP销毁目录
  83. 删除一个目录,包括它的内容。
  84. /*****
  85. *@dir – Directory to destroy
  86. *@virtual[optional]- whether a virtual directory
  87. */
  88. function destroyDir($dir, $virtual = false)
  89. {
  90. $ds = DIRECTORY_SEPARATOR;
  91. $dir = $virtual ? realpath($dir) : $dir;
  92. $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
  93. if (is_dir($dir) && $handle = opendir($dir))
  94. {
  95. while ($file = readdir($handle))
  96. {
  97. if ($file == ‘.’ || $file == ‘..’)
  98. {
  99. continue;
  100. }
  101. elseif (is_dir($dir.$ds.$file))
  102. {
  103. destroyDir($dir.$ds.$file);
  104. }
  105. else
  106. {
  107. unlink($dir.$ds.$file);
  108. }
  109. }
  110. closedir($handle);
  111. rmdir($dir);
  112. return true;
  113. }
  114. else
  115. {
  116. return false;
  117. }
  118. }
  119. 7. PHP解析 JSON 数据
  120. 与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,XML 等等。
  121. $json_string=’{“id”:1,”name”:”foo”,”email”:”foo@foobar.com”,”interest”:["wordpress","php"]} ‘;
  122. $obj=json_decode($json_string);
  123. echo $obj->name; //prints foo
  124. echo $obj->interest[1]; //prints php
  125. 8. PHP解析 XML 数据
  126. //xml string
  127. $xml_string=”
  128. Foo
  129. foo@bar.com
  130. Foobar
  131. foobar@foo.com
  132. ”;
  133. //load the xml string using simplexml
  134. $xml = simplexml_load_string($xml_string);
  135. //loop through the each node of user
  136. foreach ($xml->user as $user)
  137. {
  138. //access attribute
  139. echo $user['id'], ‘ ‘;
  140. //subnodes are accessed by -> operator
  141. echo $user->name, ‘ ‘;
  142. echo $user->email, ‘
  143. ’;
  144. }
  145. 9. PHP创建日志缩略名
  146. 创建用户友好的日志缩略名。
  147. function create_slug($string){
  148. $slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);
  149. return $slug;
  150. }
  151. 10. PHP获取客户端真实 IP 地址
  152. 该函数将获取用户的真实 IP 地址,即便他使用代理服务器。
  153. function getRealIpAddr()
  154. {
  155. if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
  156. {
  157. $ip=$_SERVER['HTTP_CLIENT_IP'];
  158. }
  159. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
  160. //to check ip is pass from proxy
  161. {
  162. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  163. }
  164. else
  165. {
  166. $ip=$_SERVER['REMOTE_ADDR'];
  167. }
  168. return $ip;
  169. }
  170. 11. PHP强制性文件下载
  171. 为用户提供强制性的文件下载功能。
  172. /********************
  173. *@file – path to file
  174. */
  175. function force_download($file)
  176. {
  177. if ((isset($file))&&(file_exists($file))) {
  178. header(“Content-length: “.filesize($file));
  179. header(‘Content-Type: application/octet-stream’);
  180. header(‘Content-Disposition: attachment; filename=”‘ . $file . ‘”‘);
  181. readfile(“$file”);
  182. } else {
  183. echo “No file selected”;
  184. }
  185. }
  186. 12. PHP创建标签云
  187. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
  188. {
  189. $minimumCount = min( array_values( $data ) );
  190. $maximumCount = max( array_values( $data ) );
  191. $spread = $maximumCount – $minimumCount;
  192. $cloudHTML = ”;
  193. $cloudTags = array();
  194. $spread == 0 && $spread = 1;
  195. foreach( $data as $tag => $count )
  196. {
  197. $size = $minFontSize + ( $count – $minimumCount )
  198. * ( $maxFontSize – $minFontSize ) / $spread;
  199. $cloudTags[] = ‘. ‘” href=”#” title=”\” . $tag .
  200. ‘\’ returned a count of ‘ . $count . ‘”>’
  201. . htmlspecialchars( stripslashes( $tag ) ) . ‘’;
  202. }
  203. return join( “\n”, $cloudTags ) . “\n”;
  204. }
  205. /**************************
  206. **** Sample usage ***/
  207. $arr = Array(‘Actionscript’ => 35, ‘Adobe’ => 22, ‘Array’ => 44, ‘Background’ => 43,
  208. ‘Blur’ => 18, ‘Canvas’ => 33, ‘Class’ => 15, ‘Color Palette’ => 11, ‘Crop’ => 42,
  209. ‘Delimiter’ => 13, ‘Depth’ => 34, ‘Design’ => 8, ‘Encode’ => 12, ‘Encryption’ => 30,
  210. ‘Extract’ => 28, ‘Filters’ => 42);
  211. echo getCloud($arr, 12, 36);
  212. 13. PHP寻找两个字符串的相似性
  213. PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。
  214. similar_text($string1, $string2, $percent);
  215. //$percent will have the percentage of similarity
  216. 14. PHP在应用程序中使用 Gravatar 通用头像
  217. 随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。
  218. /******************
  219. *@email – Email address to show gravatar for
  220. *@size – size of gravatar
  221. *@default – URL of default gravatar to use
  222. *@rating – rating of Gravatar(G, PG, R, X)
  223. */
  224. function show_gravatar($email, $size, $default, $rating)
  225. {
  226. echo ‘‘&default=’.$default.’&size=’.$size.’&rating=’.$rating.’” width=”‘.$size.’px”
  227. height=”‘.$size.’px” />’;
  228. }
  229. 15. PHP在字符断点处截断文字
  230. 所谓断字 (word break),即一个单词可在转行时断开的地方。这一函数将在断字处截断字符串。
  231. // Original PHP code by Chirp Internet: www.chirp.com.au
  232. // Please acknowledge use of this code by including this header.
  233. function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
  234. // return with no change if string is shorter than $limit
  235. if(strlen($string) return $string;
  236. // is $break present between $limit and the end of the string?
  237. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  238. if($breakpoint $string = substr($string, 0, $breakpoint) . $pad;
  239. }
  240. }
  241. return $string;
  242. }
  243. /***** Example ****/
  244. $short_string=myTruncate($long_string, 100, ‘ ‘);
  245. 16. PHP文件 Zip 压缩
  246. /* creates a compressed zip file */
  247. function create_zip($files = array(),$destination = ”,$overwrite = false) {
  248. //if the zip file already exists and overwrite is false, return false
  249. if(file_exists($destination) && !$overwrite) { return false; }
  250. //vars
  251. $valid_files = array();
  252. //if files were passed in…
  253. if(is_array($files)) {
  254. //cycle through each file
  255. foreach($files as $file) {
  256. //make sure the file exists
  257. if(file_exists($file)) {
  258. $valid_files[] = $file;
  259. }
  260. }
  261. }
  262. //if we have good files…
  263. if(count($valid_files)) {
  264. //create the archive
  265. $zip = new ZipArchive();
  266. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  267. return false;
  268. }
  269. //add the files
  270. foreach($valid_files as $file) {
  271. $zip->addFile($file,$file);
  272. }
  273. //debug
  274. //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
  275. //close the zip — done!
  276. $zip->close();
  277. //check to make sure the file exists
  278. return file_exists($destination);
  279. }
  280. else
  281. {
  282. return false;
  283. }
  284. }
  285. /***** Example Usage ***/
  286. $files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);
  287. create_zip($files, ‘myzipfile.zip’, true);
  288. 17. PHP解压缩 Zip 文件
  289. /**********************
  290. *@file – path to zip file
  291. *@destination – destination directory for unzipped files
  292. */
  293. function unzip_file($file, $destination){
  294. // create object
  295. $zip = new ZipArchive() ;
  296. // open archive
  297. if ($zip->open($file) !== TRUE) {
  298. die (’Could not open archive’);
  299. }
  300. // extract contents to destination directory
  301. $zip->extractTo($destination);
  302. // close archive
  303. $zip->close();
  304. echo ‘Archive extracted to directory’;
  305. }
  306. 18. PHP为 URL 地址预设 http 字符串
  307. 有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。
  308. if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
  309. $_POST['url'] = ‘http://’.$_POST['url'];
  310. }
  311. 19. PHP将网址字符串转换成超级链接
  312. 该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。
  313. function makeClickableLinks($text) {
  314. $text = eregi_replace(‘(((f|ht)lianqiangjavatp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
  315. ‘\1’, $text);
  316. $text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
  317. ‘\1\2’, $text);
  318. $text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
  319. ‘\1’, $text);
  320. return $text;
  321. }
  322. 20. PHP调整图像尺寸
  323. 创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。
  324. /**********************
  325. *@filename – path to the image
  326. *@tmpname – temporary path to thumbnail
  327. *@xmax – max width
  328. *@ymax – max height
  329. */
  330. function resize_image($filename, $tmpname, $xmax, $ymax)
  331. {
  332. $ext = explode(“.”, $filename);
  333. $ext = $ext[count($ext)-1];
  334. if($ext == “jpg” || $ext == “jpeg”)
  335. $im = imagecreatefromjpeg($tmpname);
  336. elseif($ext == “png”)
  337. $im = imagecreatefrompng($tmpname);
  338. elseif($ext == “gif”)
  339. $im = imagecreatefromgif($tmpname);
  340. $x = imagesx($im);
  341. $y = imagesy($im);
  342. if($x return $im;
  343. if($x >= $y) {
  344. $newx = $xmax;
  345. $newy = $newx * $y / $x;
  346. }
  347. else {
  348. $newy = $ymax;
  349. $newx = $x / $y * $newy;
  350. }
  351. $im2 = imagecreatetruecolor($newx, $newy);
  352. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
  353. return $im2;
  354. }
  355. 21. PHP检测 ajax 请求
  356. 大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。
  357. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){
  358. //If AJAX Request Then
  359. }else{
  360. //something else
  361. }
复制代码


声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
PHP的当前状态:查看网络开发趋势PHP的当前状态:查看网络开发趋势Apr 13, 2025 am 12:20 AM

PHP在现代Web开发中仍然重要,尤其在内容管理和电子商务平台。1)PHP拥有丰富的生态系统和强大框架支持,如Laravel和Symfony。2)性能优化可通过OPcache和Nginx实现。3)PHP8.0引入JIT编译器,提升性能。4)云原生应用通过Docker和Kubernetes部署,提高灵活性和可扩展性。

PHP与其他语言:比较PHP与其他语言:比较Apr 13, 2025 am 12:19 AM

PHP适合web开发,特别是在快速开发和处理动态内容方面表现出色,但不擅长数据科学和企业级应用。与Python相比,PHP在web开发中更具优势,但在数据科学领域不如Python;与Java相比,PHP在企业级应用中表现较差,但在web开发中更灵活;与JavaScript相比,PHP在后端开发中更简洁,但在前端开发中不如JavaScript。

PHP与Python:核心功能PHP与Python:核心功能Apr 13, 2025 am 12:16 AM

PHP和Python各有优势,适合不同场景。1.PHP适用于web开发,提供内置web服务器和丰富函数库。2.Python适合数据科学和机器学习,语法简洁且有强大标准库。选择时应根据项目需求决定。

PHP:网络开发的关键语言PHP:网络开发的关键语言Apr 13, 2025 am 12:08 AM

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP:许多网站的基础PHP:许多网站的基础Apr 13, 2025 am 12:07 AM

PHP成为许多网站首选技术栈的原因包括其易用性、强大社区支持和广泛应用。1)易于学习和使用,适合初学者。2)拥有庞大的开发者社区,资源丰富。3)广泛应用于WordPress、Drupal等平台。4)与Web服务器紧密集成,简化开发部署。

超越炒作:评估当今PHP的角色超越炒作:评估当今PHP的角色Apr 12, 2025 am 12:17 AM

PHP在现代编程中仍然是一个强大且广泛使用的工具,尤其在web开发领域。1)PHP易用且与数据库集成无缝,是许多开发者的首选。2)它支持动态内容生成和面向对象编程,适合快速创建和维护网站。3)PHP的性能可以通过缓存和优化数据库查询来提升,其广泛的社区和丰富生态系统使其在当今技术栈中仍具重要地位。

PHP中的弱参考是什么?什么时候有用?PHP中的弱参考是什么?什么时候有用?Apr 12, 2025 am 12:13 AM

在PHP中,弱引用是通过WeakReference类实现的,不会阻止垃圾回收器回收对象。弱引用适用于缓存系统和事件监听器等场景,需注意其不能保证对象存活,且垃圾回收可能延迟。

解释PHP中的__ Invoke Magic方法。解释PHP中的__ Invoke Magic方法。Apr 12, 2025 am 12:07 AM

\_\_invoke方法允许对象像函数一样被调用。1.定义\_\_invoke方法使对象可被调用。2.使用$obj(...)语法时,PHP会执行\_\_invoke方法。3.适用于日志记录和计算器等场景,提高代码灵活性和可读性。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
3 周前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您听不到任何人,如何修复音频
3 周前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解锁Myrise中的所有内容
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),