Rumah  >  Artikel  >  pembangunan bahagian belakang  >  给大家分享21个常用的PHP函数代码段

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

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


Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn