We will share 21 common PHP function code segments.

Source: Internet
Author: User
Tags ziparchive
We will share 21 common PHP function code segments.
Share 21 common PHP function code segments

  1. 1. PHP can read random strings
  2. This code creates a readable string that is closer to a word in the dictionary and is practical and password-verified.
  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 do not need readable strings, use this function instead to create a random string as your random password.
  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; $ I <$ l; $ I ++ ){
  29. $ Rand. = $ c [rand () % strlen ($ c)];
  30. }
  31. Return $ rand;
  32. }
  33. 3. PHP-encoded email address
  34. This code can be used to encode any email address as an html character entity to prevent being collected 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 may be the most common web form verification. in addition to verifying the email address, this code can also choose to check MX records in the DNS to which the email domain belongs, making email verification 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 listing directory content
  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. Delete 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. parse JSON data in PHP
  122. Like most popular Web services, such as twitter, which provides data through open APIs, it always knows how to parse various transfer formats of API data, including JSON and XML.
  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. name scaling of PHP creation logs
  148. Create a user-friendly log scaling name.
  149. Function create_slug ($ string ){
  150. $ Slug = preg_replace ('/[^ A-Za-z0-9-] +/', '-', $ string );
  151. Return $ slug;
  152. }
  153. 10. PHP obtains the real IP address of the client.
  154. This function will obtain the real IP address of the user, even if he uses the 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_FOR '])
  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. It provides users with mandatory file download functions.
  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. create a tag cloud in PHP
  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 paster' => 11, 'crop' => 42,
  211. 'Delimiter' => 13, 'dest' => 34, 'design' => 8, 'encode' => 12, 'encryption' => 30,
  212. 'Effect' => 28, 'Filters '=> 42 );
  213. Echo getCloud ($ arr, 12, 36 );
  214. 13. search for similarity between two strings in PHP
  215. PHP provides a rarely used similar_text function, but this function is very useful for comparing two strings and returning a percentage of similarity.
  216. Similar_text ($ string1, $ string2, $ percent );
  217. // $ Percent will have the percentage of similarity
  218. 14. use the Gravatar profile picture in PHP applications
  219. As WordPress becomes increasingly popular, Gravatar also becomes popular. Gravatar provides easy-to-use APIs, making it easy to include them in applications.
  220. /******************
  221. * @ Email-Email address to show gravatar
  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 the character breakpoint
  232. Word break refers to the place where a word can be broken when it is switched. This function truncates the string at the break.
  233. // Original PHP code by chiririnternet: 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. Zip compression of PHP files
  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 ins, $ 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. Optional files=array('file1.jpg ', 'file2.jpg', 'file3.gif ');
  291. Create_zip ($ files, 'myzipfile.zip ', true );
  292. 17. decompress the Zip file in PHP.
  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-> extrac.pdf ($ destination );
  306. // Close archive
  307. $ Zip-> close ();
  308. Echo 'Archive extracted to directory ';
  309. }
  310. 18. PHP presets the http string for the URL address
  311. Sometimes you need to accept URL input in some forms, but few users add http: // fields. this code will add this field to the URL.
  312. If (! Preg_match ("/^ (http | ftp):/", $ _ POST ['URL']) {
  313. $ _ POST ['URL'] = 'http: // '. $ _ POST ['URL'];
  314. }
  315. 19. PHP converts the URL string into a hyperlink
  316. This function converts the URL and e-mail address strings into clickable superlinks.
  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. '\ 1 \ 2', $ 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 adjusted Image size
  327. Creating image thumbnails takes a long time. This code helps you understand the thumbnails logic.
  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 detects ajax requests
  361. Most JavaScript frameworks, such as jquery and Mootools, send additional HTTP_X_REQUESTED_WITH header information when sending Ajax requests. the header is an ajax request, therefore, you can detect Ajax requests on the server side.
  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. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.