Home > Backend Development > PHP Tutorial > Share with you 21 commonly used PHP function code snippets

Share with you 21 commonly used PHP function code snippets

WBOY
Release: 2016-07-25 09:08:31
Original
1043 people have browsed it
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<=$max; $i++)
  14. {
  15. $password.=$conso[rand(0,19)];
  16. $password.=$vocal[rand(0,4)];
  17. }
  18. return $password;
  19. }
  20. 2. PHP generates a random string
  21. 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.
  22. /*************
  23. *@l – length of random string
  24. */
  25. function generate_rand($l){
  26. $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789″;
  27. srand((double)microtime()*1000000);
  28. for($i=0; < $l; $i++) {
  29. $rand.= $c[rand()%strlen($c)];
  30. }
  31. return $rand;
  32. }
  33. 3. PHP encode email address
  34. Use this code, Any email address can be encoded as html character entities to prevent collection by spam programs.
  35. function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class=”emailencoder”' )
  36. {
  37. // remplazar aroba y puntos
  38. $email = str_replace( '@', '@', $email);
  39. $email = str_replace('.', '.', $email);
  40. $email = str_split($email, 5);
  41. $linkText = str_replace('@', '@', $linkText);
  42. $linkText = str_replace('.', '.', $linkText);
  43. $linkText = str_split($linkText, 5);
  44. $part1 = '$part2 = 'ilto:';
  45. $part3 = '" '. $attrs .' >';
  46. $part4 = '';
  47. $encoded = '';
  48. return $encoded;
  49. }
  50. 4. PHP verification email address
  51. 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.
  52. function is_valid_email($email, $test_mx = false)
  53. {
  54. if(eregi(“^([_a-z0-9-]+)(.[_a-z0-9 -]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$”, $email))
  55. if ($test_mx)
  56. {
  57. list($username, $domain) = split(“@”, $email);
  58. return getmxrr($domain, $mxrecords);
  59. }
  60. else
  61. return true;
  62. else
  63. return false ;
  64. }
  65. 5. PHP list directory contents
  66. function list_files($dir)
  67. {
  68. if(is_dir($dir))
  69. {
  70. if($handle = opendir($dir))
  71. {
  72. while( ($file = readdir($handle)) !== false)
  73. {
  74. if($file != “.” && $file != “..” && $file != “Thumbs.db”)
  75. {
  76. echo ''.$file.'
  77. '.”n”;
  78. }
  79. }
  80. closedir($handle);
  81. }
  82. }
  83. }
  84. 6. PHP Destroy Directory
  85. Deletes a directory, including its contents.
  86. /*****
  87. *@dir – Directory to destroy
  88. *@virtual[optional]- whether a virtual directory
  89. */
  90. function destroyDir($dir, $virtual = false)
  91. {
  92. $ds = DIRECTORY_SEPARATOR;
  93. $dir = $virtual ? realpath($dir) : $dir;
  94. $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
  95. if (is_dir($dir) && $handle = opendir($dir))
  96. {
  97. while ( $file = readdir($handle))
  98. {
  99. if ($file == '.' || $file == '..')
  100. {
  101. continue;
  102. }
  103. elseif (is_dir($dir.$ds. $file))
  104. {
  105. destroyDir($dir.$ds.$file);
  106. }
  107. else
  108. {
  109. unlink($dir.$ds.$file);
  110. }
  111. }
  112. closedir($handle);
  113. rmdir($dir);
  114. return true;
  115. }
  116. else
  117. {
  118. return false;
  119. }
  120. }
  121. 7. PHP parses JSON data
  122. 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.
  123. $json_string='{"id":1,"name":"foo","email":"foo@foobar.com","interest":["wordpress","php"]} ';
  124. $obj=json_decode($json_string);
  125. echo $obj->name; //prints foo
  126. echo $obj->interest[1]; //prints php
  127. 8. PHP parses XML data
  128. // xml string
  129. $xml_string=”
  130. Foo
  131. foo@bar.com
  132. Foobar
  133. foobar@foo.com
  134. ”;
  135. //load the xml string using simplexml
  136. $xml = simplexml_load_string($xml_string) ;
  137. //loop through the each node of user
  138. foreach ($xml->user as $user)
  139. {
  140. //access attribute
  141. echo $user['id'], ' ';
  142. //subnodes are accessed by -> operator
  143. echo $user->name, ' ';
  144. echo $user->email, '
  145. ';
  146. }
  147. 9. PHP creates log abbreviation
  148. Create user-friendly logs Abbreviation.
  149. function create_slug($string){
  150. $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
  151. return $slug;
  152. }
  153. 10 . PHP gets the real IP address of the client
  154. This function will get the real IP address of the user, even if he uses a proxy server.
  155. function getRealIpAddr()
  156. {
  157. if (!emptyempty($_SERVER['HTTP_CLIENT_IP']))
  158. {
  159. $ip=$_SERVER['HTTP_CLIENT_IP'];
  160. }
  161. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_F OR ']))
  162. //to check ip is pass from proxy
  163. {
  164. $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
  165. }
  166. else
  167. {
  168. $ip=$_SERVER['REMOTE_ADDR'];
  169. }
  170. return $ip;
  171. }
  172. 11. PHP mandatory file download
  173. provides users with mandatory file download function.
  174. /********************
  175. *@file – path to file
  176. */
  177. function force_download($file)
  178. {
  179. if ((isset($file))&&(file_exists($file))) {
  180. header(“Content-length: “.filesize ($file));
  181. header('Content-Type: application/octet-stream');
  182. header('Content-Disposition: attachment; filename="' . $file . '"');
  183. readfile("$ file”);
  184. } else {
  185. echo “No file selected”;
  186. }
  187. }
  188. 12. PHP creates tag cloud
  189. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
  190. {
  191. $minimumCount = min( array_values( $data ) );
  192. $maximumCount = max( array_values( $data ) );
  193. $spread = $maximumCount – $minimumCount;
  194. $cloudHTML = ”;
  195. $cloudTags = array( );
  196. $spread == 0 && $spread = 1;
  197. foreach( $data as $tag => $count )
  198. {
  199. $size = $minFontSize + ( $count – $minimumCount )
  200. * ( $ maxFontSize – $minFontSize ) / $spread;
  201. $cloudTags[] = '. '" href="#" title="" . $tag .
  202. '' returned a count of ' . $count . '">'
  203. . htmlspecialchars( stripslashes( $tag ) ) . '';
  204. }
  205. return join( "n", $cloudTags ) . "n";
  206. }
  207. /**************************
  208. **** Sample usage ***/
  209. $arr = Array(' Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43,
  210. 'Blur' => 18, 'Canvas' => 33, 'Class ' => 15, 'Color Palette' => 11, 'Crop' => 42,
  211. 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode ' => 12, 'Encryption' => 30,
  212. 'Extract' => 28, 'Filters' => 42);
  213. echo getCloud($arr, 12, 36);
  214. 13. PHP search Similarity of two strings
  215. PHP provides a rarely used similar_text function, but this function is very useful for comparing two strings and returning the percentage of similarity.
  216. similar_text($string1, $string2, $percent);
  217. //$percent will have the percentage of similarity
  218. 14. PHP uses Gravatar in applications Universal avatar
  219. 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.
  220. /******************
  221. *@email – Email address to show gravatar for
  222. *@size – size of gravatar
  223. *@default – URL of default gravatar to use
  224. *@rating – rating of Gravatar(G, PG, R, X)
  225. */
  226. function show_gravatar($email, $size, $default, $rating)
  227. {
  228. echo ''&default='.$default.'&size='.$size.'&rating= '.$rating.'" width="'.$size.'px"
  229. height="'.$size.'px" />';
  230. }
  231. 15. PHP truncates text at character breakpoints
  232. 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.
  233. // Original PHP code by Chirp Internet: www.chirp.com.au
  234. // Please acknowledge use of this code by including this header.
  235. function myTruncate($string, $limit, $break=”.”, $pad=”…”) {
  236. // return with no change if string is shorter than $limit
  237. if(strlen($string) <= $limit)
  238. return $string;
  239. // is $break present between $limit and the end of the string?
  240. if(false !== ($breakpoint = strpos($string, $break, $limit))) {
  241. if($breakpoint < strlen($string) – 1) {
  242. $string = substr($string, 0, $breakpoint) . $pad;
  243. }
  244. }
  245. return $string;
  246. }
  247. /***** Example ****/
  248. $short_string=myTruncate($long_string, 100, ‘ ‘);
  249. 16. PHP文件 Zip 压缩
  250. /* creates a compressed zip file */
  251. function create_zip($files = array(),$destination = ”,$overwrite = false) {
  252. //if the zip file already exists and overwrite is false, return false
  253. if(file_exists($destination) && !$overwrite) { return false; }
  254. //vars
  255. $valid_files = array();
  256. //if files were passed in…
  257. if(is_array($files)) {
  258. //cycle through each file
  259. foreach($files as $file) {
  260. //make sure the file exists
  261. if(file_exists($file)) {
  262. $valid_files[] = $file;
  263. }
  264. }
  265. }
  266. //if we have good files…
  267. if(count($valid_files)) {
  268. //create the archive
  269. $zip = new ZipArchive();
  270. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  271. return false;
  272. }
  273. //add the files
  274. foreach($valid_files as $file) {
  275. $zip->addFile($file,$file);
  276. }
  277. //debug
  278. //echo ‘The zip archive contains ‘,$zip->numFiles,’ files with a status of ‘,$zip->status;
  279. //close the zip — done!
  280. $zip->close();
  281. //check to make sure the file exists
  282. return file_exists($destination);
  283. }
  284. else
  285. {
  286. return false;
  287. }
  288. }
  289. /***** Example Usage ***/
  290. $files=array(‘file1.jpg’, ‘file2.jpg’, ‘file3.gif’);
  291. create_zip($files, ‘myzipfile.zip’, true);
  292. 17. PHP解压缩 Zip 文件
  293. /**********************
  294. *@file – path to zip file
  295. *@destination – destination directory for unzipped files
  296. */
  297. function unzip_file($file, $destination){
  298. // create object
  299. $zip = new ZipArchive() ;
  300. // open archive
  301. if ($zip->open($file) !== TRUE) {
  302. die (’Could not open archive’);
  303. }
  304. // extract contents to destination directory
  305. $zip->extractTo($destination);
  306. // close archive
  307. $zip->close();
  308. echo ‘Archive extracted to directory’;
  309. }
  310. 18. PHP为 URL 地址预设 http 字符串
  311. 有时需要接受一些表单中的网址输入,但用户很少添加 http:// 字段,此代码将为网址添加该字段。
  312. if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
  313. $_POST['url'] = ‘http://’.$_POST['url'];
  314. }
  315. 19. PHP将网址字符串转换成超级链接
  316. 该函数将 URL 和 E-mail 地址字符串转换为可点击的超级链接。
  317. function makeClickableLinks($text) {
  318. $text = eregi_replace(‘(((f|ht)lianqiangjavatp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
  319. ‘1’, $text);
  320. $text = eregi_replace(‘([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)’,
  321. ‘12’, $text);
  322. $text = eregi_replace(‘([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})’,
  323. ‘1’, $text);
  324. return $text;
  325. }
  326. 20. PHP调整图像尺寸
  327. 创建图像缩略图需要许多时间,此代码将有助于了解缩略图的逻辑。
  328. /**********************
  329. *@filename – path to the image
  330. *@tmpname – temporary path to thumbnail
  331. *@xmax – max width
  332. *@ymax – max height
  333. */
  334. function resize_image($filename, $tmpname, $xmax, $ymax)
  335. {
  336. $ext = explode(“.”, $filename);
  337. $ext = $ext[count($ext)-1];
  338. if($ext == “jpg” || $ext == “jpeg”)
  339. $im = imagecreatefromjpeg($tmpname);
  340. elseif($ext == “png”)
  341. $im = imagecreatefrompng($tmpname);
  342. elseif($ext == “gif”)
  343. $im = imagecreatefromgif($tmpname);
  344. $x = imagesx($im);
  345. $y = imagesy($im);
  346. if($x <= $xmax && $y <= $ymax)
  347. return $im;
  348. if($x >= $y) {
  349. $newx = $xmax;
  350. $newy = $newx * $y / $x;
  351. }
  352. else {
  353. $newy = $ymax;
  354. $newx = $x / $y * $newy;
  355. }
  356. $im2 = imagecreatetruecolor($newx, $newy);
  357. imagecopyresized($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
  358. return $im2;
  359. }
  360. 21. PHP检测 ajax 请求
  361. 大多数的 JavaScript 框架如 jquery,Mootools 等,在发出 Ajax 请求时,都会发送额外的 HTTP_X_REQUESTED_WITH 头部信息,头当他们一个ajax请求,因此你可以在服务器端侦测到 Ajax 请求。
  362. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == ‘xmlhttprequest’){
  363. //If AJAX Request Then
  364. }else{
  365. //something else
  366. }
Copy code


source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template