search
HomeBackend DevelopmentPHP TutorialShare with you 21 commonly used PHP function code snippets

Share 21 commonly used PHP function code snippets
  1. 1. PHP Readable Random String
  2. This code will create a readable string that is closer to the word in the dictionary, practical and has password verification capabilities.
  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 generates a random string
  20. If you don’t need a readable string, use this function instead , you can create a random string as the user's random password, etc.
  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; $rand.= $c[rand()%strlen($c)];
  28. }
  29. return $rand;
  30. }
  31. 3. PHP encode email address
  32. Use this code, Any email address can be encoded as html character entities to prevent collection by spam programs.
  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 verification email address
  49. Email verification is perhaps the most commonly used web form verification. In addition to verifying the email address, this code can also choose to check the MX in the DNS to which the email domain belongs. Records to make the email verification function more powerful.
  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 list directory contents
  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 Destroy Directory
  83. Deletes a directory, including its contents.
  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 parses JSON data
  120. Same as most popular web services such as twitter provide data through open APIs , it always knows how to parse various transmission formats of API data, including JSON, XML, etc.
  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 parses XML data
  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 creates log abbreviation
  146. Create user-friendly logs Abbreviation.
  147. function create_slug($string){
  148. $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
  149. return $slug;
  150. }
  151. 10 . PHP gets the real IP address of the client
  152. This function will get the real IP address of the user, even if he uses a proxy server.
  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_F OR ']))
  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 mandatory file download
  171. provides users with mandatory file download function.
  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 creates tag cloud
  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 search Similarity of two strings
  213. PHP provides a rarely used similar_text function, but this function is very useful for comparing two strings and returning the percentage of similarity.
  214. similar_text($string1, $string2, $percent);
  215. //$percent will have the percentage of similarity
  216. 14. PHP uses Gravatar in applications Universal avatar
  217. As WordPress becomes more and more popular, Gravatar also Then it became popular. Since Gravatar provides an easy-to-use API, incorporating it into your application becomes easy.
  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 truncates text at character breakpoints
  230. The so-called word break is where a word can be broken when changing lines. This function will truncate the string at the 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. ‘12’, $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. }
Copy code


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use