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
What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

PHP Dependency Injection: Boost Code MaintainabilityPHP Dependency Injection: Boost Code MaintainabilityMay 07, 2025 pm 02:37 PM

Dependency injection provides object dependencies through external injection in PHP, improving the maintainability and flexibility of the code. Its implementation methods include: 1. Constructor injection, 2. Set value injection, 3. Interface injection. Using dependency injection can decouple, improve testability and flexibility, but attention should be paid to the possibility of increasing complexity and performance overhead.

How to Implement Dependency Injection in PHPHow to Implement Dependency Injection in PHPMay 07, 2025 pm 02:33 PM

Implementing dependency injection (DI) in PHP can be done by manual injection or using DI containers. 1) Manual injection passes dependencies through constructors, such as the UserService class injecting Logger. 2) Use DI containers to automatically manage dependencies, such as the Container class to manage Logger and UserService. Implementing DI can improve code flexibility and testability, but you need to pay attention to traps such as overinjection and service locator anti-mode.

What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

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