当前位置:Gxlcms > PHP教程 > 给大家分享21个常用的PHP函数代码段

给大家分享21个常用的PHP函数代码段

时间:2021-07-01 10:21:17 帮助过:10人阅读

分享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<=$max; $i++)
  14. {
  15. $password.=$conso[rand(0,19)];
  16. $password.=$vocal[rand(0,4)];
  17. }
  18. return $password;
  19. }
  20. 2. PHP生成一个随机字符串
  21. 如果不需要可阅读的字符串,使用此函数替代,即可创建一个随机字符串,作为用户的随机密码等。
  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编码电子邮件地址
  34. 使用此代码,可以将任何电子邮件地址编码为 html 字符实体,以防止被垃圾邮件程序收集。
  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验证邮件地址
  51. 电子邮件验证也许是中最常用的网页表单验证,此代码除了验证电子邮件地址,也可以选择检查邮件域所属 DNS 中的 MX 记录,使邮件验证功能更加强大。
  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列出目录内容
  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销毁目录
  85. 删除一个目录,包括它的内容。
  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解析 JSON 数据
  122. 与大多数流行的 Web 服务如 twitter 通过开放 API 来提供数据一样,它总是能够知道如何解析 API 数据的各种传送格式,包括 JSON,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解析 XML 数据
  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创建日志缩略名
  148. 创建用户友好的日志缩略名。
  149. function create_slug($string){
  150. $slug=preg_replace(‘/[^A-Za-z0-9-]+/’, ‘-’, $string);
  151. return $slug;
  152. }
  153. 10. PHP获取客户端真实 IP 地址
  154. 该函数将获取用户的真实 IP 地址,即便他使用代理服务器。
  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强制性文件下载
  173. 为用户提供强制性的文件下载功能。
  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创建标签云
  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寻找两个字符串的相似性
  215. PHP 提供了一个极少使用的 similar_text 函数,但此函数非常有用,用于比较两个字符串并返回相似程度的百分比。
  216. similar_text($string1, $string2, $percent);
  217. //$percent will have the percentage of similarity
  218. 14. PHP在应用程序中使用 Gravatar 通用头像
  219. 随着 WordPress 越来越普及,Gravatar 也随之流行。由于 Gravatar 提供了易于使用的 API,将其纳入应用程序也变得十分方便。
  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在字符断点处截断文字
  232. 所谓断字 (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. ‘\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调整图像尺寸
  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. }

人气教程排行