使用的php代碼

  1. 1. PHP可閱讀隨機字符串
  2. // 此代碼將創建一個可閱讀的字符串,使其更接近詞典中的單詞,實用且具有密碼驗證功能。
  3. functionreadable_random_string($length= 6) {
  4. $conso= array("b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "r", "s", "t", "v", "w", "x", "y", "z");
  5. $vocal= array("a", "e", "i", "o", "u");
  6. $password= "";
  7. srand ( ( double ) microtime () * 1000000 );
  8. $max= $length/ 2;
  9. for($i= 1; $i<= $max; $i++) {
  10. $password.= $conso[rand ( 0, 19 )];
  11. $password.= $vocal[rand ( 0, 4 )];
  12. }
  13. return$password;
  14. }
  15. //  2. PHP生成一個隨機字符串
  16. //  如果不需要可閱讀的字符串,使用此函數替代,即可創建一個隨機字符串,作爲用戶的隨機密碼等。
  17. functiongenerate_rand($l) {
  18. $c= "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  19. srand ( ( double ) microtime () * 1000000 );
  20. for($i= 0; $i< $l; $i++) {
  21. $rand.= $c[rand () % strlen( $c)];
  22. }
  23. return$rand;
  24. }
  25. //  3. PHP編碼電子郵件地址
  26. //  使用此代碼,可以將任何電子郵件地址編碼爲 html 字符實體,以防止被垃圾郵件程序收集。
  27. functionencode_email($email= '[email protected]', $linkText= 'Contact Us', $attrs= 'class="emailencoder"') {
  28. // remplazar aroba y puntos
  29. $email= str_replace( '@', '@', $email);
  30. $email= str_replace( '.', '.', $email);
  31. $email= str_split( $email, 5 );
  32. $linkText= str_replace( '@', '@', $linkText);
  33. $linkText= str_replace( '.', '.', $linkText);
  34. $linkText= str_split( $linkText, 5 );
  35. $part1= '<a href="ma';
  36. $part2= 'ilto:';
  37. $part3= '" '. $attrs. ' >';
  38. $part4= '</a>';
  39. $encoded= '<script type="text/javascript">';
  40. $encoded.= "document.write('$part1');";
  41. $encoded.= "document.write('$part2');";
  42. foreach( $emailas$e) {
  43. $encoded.= "document.write('$e');";
  44. }
  45. $encoded.= "document.write('$part3');";
  46. foreach( $linkTextas$l) {
  47. $encoded.= "document.write('$l');";
  48. }
  49. $encoded.= "document.write('$part4');";
  50. $encoded.= '</script>';
  51. return$encoded;
  52. }
  53. //  4. PHP驗證郵件地址
  54. //  電子郵件驗證也許是中最常用的網頁表單驗證,此代碼除了驗證電子郵件地址,也可以選擇檢查郵件域所屬 DNS 中的 MX 記錄,使郵件驗證功能更加強大。
  55. functionis_valid_email($email, $test_mx= false) {
  56. if(eregi( "^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$", $email))
  57. if($test_mx) {
  58. list ( $username, $domain) = split ( "@", $email);
  59. returngetmxrr( $domain, $mxrecords);
  60. } else
  61. returntrue;
  62. else
  63. returnfalse;
  64. }
  65. //  5. PHP列出目錄內容
  66. functionlist_files($dir) {
  67. if(is_dir( $dir)) {
  68. if($handle= opendir ( $dir)) {
  69. while( ($file= readdir ( $handle)) !== false ) {
  70. if($file!= "."&& $file!= ".."&& $file!= "Thumbs.db") {
  71. echo'<a target="_blank" href="'. $dir. $file. '">'. $file. '</a><br>'. "n";
  72. }
  73. }
  74. closedir( $handle);
  75. }
  76. }
  77. }
  78. //  6. PHP銷燬目錄
  79. //  刪除一個目錄,包括它的內容。
  80. functiondestroyDir($dir, $virtual= false) {
  81. $ds= DIRECTORY_SEPARATOR;
  82. $dir= $virtual? realpath( $dir) : $dir;
  83. $dir= substr( $dir, - 1 ) == $ds? substr( $dir, 0, - 1 ) : $dir;
  84. if(is_dir( $dir) && $handle= opendir ( $dir)) {
  85. while( $file= readdir ( $handle) ) {
  86. if($file== '.'|| $file== '..') {
  87. continue;
  88. } elseif(is_dir( $dir. $ds. $file)) {
  89. destroyDir ( $dir. $ds. $file);
  90. } else{
  91. unlink ( $dir. $ds. $file);
  92. }
  93. }
  94. closedir( $handle);
  95. rmdir( $dir);
  96. returntrue;
  97. } else{
  98. returnfalse;
  99. }
  100. }
  101. //  7. PHP解析 JSON 數據
  102. //  與大多數流行的 Web 服務如 twitter 通過開放 API 來提供數據一樣,它總是能夠知道如何解析 API 數據的各種傳送格式,包括 JSON,XML 等等。
  103. $json_string= '{"id":1,"name":"foo","email":"[email protected]","interest":["wordpress","php"]} ';
  104. $obj= json_decode ( $json_string);
  105. echo$obj->name; //prints foo
  106. echo$obj->interest [1]; //prints php
  107. //  8. PHP解析 XML 數據
  108. //xml string
  109. $xml_string= "<?xml version='1.0'?>
  110. <users>
  111. <user id='398'>
  112. <name>Foo</name>
  113. <email>'\"mailto:[email protected]\"'>[email protected]</name>
  114. </user>
  115. <user id='867'>
  116. <name>Foobar</name>
  117. <email>'\"mailto:[email protected]\"'>[email protected]</name>
  118. </user>
  119. </users>";
  120. //load the xml string using simplexml
  121. $xml= simplexml_load_string ( $xml_string);
  122. //loop through the each node of user
  123. foreach( $xml->user as$user) {
  124. //access attribute
  125. echo$user['id'], ' ';
  126. //subnodes are accessed by -> operator
  127. echo$user->name, ' ';
  128. echo$user->email, '<br />';
  129. }
  130. //  9. PHP創建日誌縮略名
  131. //  創建用戶友好的日誌縮略名。
  132. functioncreate_slug($string) {
  133. $slug= preg_replace ( '/[^A-Za-z0-9-]+/', '-', $string);
  134. return$slug;
  135. }
  136. //  10. PHP獲取客戶端真實 IP 地址
  137. //  該函數將獲取用戶的真實 IP 地址,即便他使用代理服務器。
  138. functiongetRealIpAddr() {
  139. if(! emptyempty ( $_SERVER['HTTP_CLIENT_IP'] )) {
  140. $ip= $_SERVER['HTTP_CLIENT_IP'];
  141. } elseif(! emptyempty ( $_SERVER['HTTP_X_FORWARDED_FOR'] )) //to check ip is pass from proxy
  142. {
  143. $ip= $_SERVER['HTTP_X_FORWARDED_FOR'];
  144. } else{
  145. $ip= $_SERVER['REMOTE_ADDR'];
  146. }
  147. return$ip;
  148. }
  149. //  11. PHP強制性文件下載
  150. //  爲用戶提供強制性的文件下載功能。
  151. functionforce_download($file) {
  152. if((isset ( $file)) && (file_exists( $file))) {
  153. header ( "Content-length: ". filesize( $file) );
  154. header ( 'Content-Type: application/octet-stream');
  155. header ( 'Content-Disposition: attachment; filename="'. $file. '"');
  156. readfile ( "$file");
  157. } else{
  158. echo"No file selected";
  159. }
  160. }
  161. //  12. PHP創建標籤雲
  162. functiongetCloud($data= array(), $minFontSize= 12, $maxFontSize= 30) {
  163. $minimumCount= min ( array_values( $data) );
  164. $maximumCount= max ( array_values( $data) );
  165. $spread= $maximumCount- $minimumCount;
  166. $cloudHTML= '';
  167. $cloudTags= array();
  168. $spread== 0 && $spread= 1;
  169. foreach( $dataas$tag=> $count) {
  170. $size= $minFontSize+ ($count- $minimumCount) * ($maxFontSize- $minFontSize) / $spread;
  171. $cloudTags[] = '<a style="font-size: '. floor( $size) . 'px'. '" href="#" title="'' . $tag . '' returned a count of '. $count. '">'. htmlspecialchars ( stripslashes( $tag) ) . '</a>';
  172. }
  173. returnjoin ( "n", $cloudTags) . "n";
  174. }
  175. /**************************
  176. $arr = Array ('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44, 'Background' => 43, 'Blur' => 18, 'Canvas' => 33, 'Class' => 15, 'Color Palette' => 11, 'Crop' => 42, 'Delimiter' => 13, 'Depth' => 34, 'Design' => 8, 'Encode' => 12, 'Encryption' => 30, 'Extract' => 28, 'Filters' => 42 );
  177. echo getCloud ( $arr, 12, 36 );
  178. //  13. PHP尋找兩個字符串的相似性
  179. //  PHP 提供了一個極少使用的 similar_text 函數,但此函數非常有用,用於比較兩個字符串並返回相似程度的百分比。
  180. similar_text ( $string1, $string2, $percent );
  181. //$percent will have the percentage of similarity
  182. //  14. PHP在應用程序中使用 Gravatar 通用頭像
  183. //  隨着 WordPress 越來越普及,Gravatar 也隨之流行。由於 Gravatar 提供了易於使用的 API,將其納入應用程序也變得十分方便。
  184. function show_gravatar($email, $size, $default, $rating) {
  185. echo '<img src="http://www.gravatar.com/avatar.php?gravatar_id=' . md5 ( $email ) . '&default=' . $default . '&size=' . $size . '&rating=' . $rating . '" width="' . $size . 'px"
  186. height="' . $size . 'px" />';
  187. }
  188. //  15. PHP在字符斷點處截斷文字
  189. //  所謂斷字 (word break),即一個單詞可在轉行時斷開的地方。這一函數將在斷字處截斷字符串。
  190. function myTruncate($string, $limit, $break = ".", $pad = "...") {
  191. // return with no change if string is shorter than $limit
  192. if (strlen ( $string ) <= $limit)
  193. return $string;
  194. // is $break present between $limit and the end of the string?
  195. if (false !== ($breakpoint = strpos ( $string, $break, $limit ))) {
  196. if ($breakpoint < strlen ( $string ) - 1) {
  197. $string = substr ( $string, 0, $breakpoint ) . $pad;
  198. }
  199. }
  200. return $string;
  201. }
  202. /***** Example ****/
  203. $short_string= myTruncate ( $long_string, 100, ' ');
  204. //  16. PHP文件 Zip 壓縮
  205. functioncreate_zip($files= array(), $destination= '', $overwrite= false) {
  206. //if the zip file already exists and overwrite is false, return false
  207. if(file_exists( $destination) && ! $overwrite) {
  208. returnfalse;
  209. }
  210. //vars
  211. $valid_files= array();
  212. //if files were passed in...
  213. if(is_array( $files)) {
  214. //cycle through each file
  215. foreach( $filesas$file) {
  216. //make sure the file exists
  217. if(file_exists( $file)) {
  218. $valid_files[] = $file;
  219. }
  220. }
  221. }
  222. //if we have good files...
  223. if(count( $valid_files)) {
  224. //create the archive
  225. $zip= newZipArchive ();
  226. if($zip->open ( $destination, $overwrite? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE ) !== true) {
  227. returnfalse;
  228. }
  229. //add the files
  230. foreach( $valid_filesas$file) {
  231. $zip->addFile ( $file, $file);
  232. }
  233. //debug
  234. //echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
  235. //close the zip -- done!
  236. $zip->close ();
  237. //check to make sure the file exists
  238. returnfile_exists( $destination);
  239. } else{
  240. returnfalse;
  241. }
  242. }
  243. /***** Example Usage ***/
  244. $files= array('file1.jpg', 'file2.jpg', 'file3.gif');
  245. create_zip ( $files, 'myzipfile.zip', true );
  246. //  17. PHP解壓縮 Zip 文件
  247. functionunzip_file($file, $destination) {
  248. // create object
  249. $zip= newZipArchive ();
  250. // open archive
  251. if($zip->open ( $file) !== TRUE) {
  252. die(’Could not open archive’)
  253. ;
  254. }
  255. // extract contents to destination directory
  256. $zip->extractTo ( $destination);
  257. // close archive
  258. $zip->close ();
  259. echo'Archive extracted to directory';
  260. }
  261. //  18. PHP爲 URL 地址預設 http 字符串
  262. //  有時需要接受一些表單中的網址輸入,但用戶很少添加 http:// 字段,此代碼將爲網址添加該字段。
  263. if(! preg_match ( "/^(http|ftp):/", $_POST['url'] )) {
  264. $_POST['url'] = 'http://'. $_POST['url'];
  265. }
  266. //  19. PHP將網址字符串轉換成超級鏈接
  267. //  該函數將 URL 和 E-mail 地址字符串轉換爲可點擊的超級鏈接。
  268. functionmakeClickableLinks($text) {
  269. $text= eregi_replace( '(((f|ht){1}tp://)[-a-zA-Z0-9@:%_+.~#?&//=]+)', '<a href="1">1</a>', $text);
  270. $text= eregi_replace( '([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_+.~#?&//=]+)', '1<a href="http://2">2</a>', $text);
  271. $text= eregi_replace( '([_.0-9a-z-]+@([0-9a-z][0-9a-z-]+.)+[a-z]{2,3})', '<a href="mailto:1">1</a>', $text);
  272. return$text;
  273. }
  274. //  20. PHP調整圖像尺寸
  275. //  創建圖像縮略圖需要許多時間,此代碼將有助於瞭解縮略圖的邏輯。
  276. functionresize_image($filename, $tmpname, $xmax, $ymax) {
  277. $ext= explode( ".", $filename);
  278. $ext= $ext[count( $ext) - 1];
  279. if($ext== "jpg"|| $ext== "jpeg")
  280. $im= imagecreatefromjpeg ( $tmpname);
  281. elseif($ext== "png")
  282. $im= imagecreatefrompng ( $tmpname);
  283. elseif($ext== "gif")
  284. $im= imagecreatefromgif ( $tmpname);
  285. $x= imagesx ( $im);
  286. $y= imagesy ( $im);
  287. if($x<= $xmax&& $y<= $ymax)
  288. return$im;
  289. if($x>= $y) {
  290. $newx= $xmax;
  291. $newy= $newx* $y/ $x;
  292. } else{
  293. $newy= $ymax;
  294. $newx= $x/ $y* $newy;
  295. }
  296. $im2= imagecreatetruecolor ( $newx, $newy);
  297. imagecopyresized ( $im2, $im, 0, 0, 0, 0, floor( $newx), floor( $newy), $x, $y);
  298. return$im2;
  299. }
  300. //  21. PHP檢測 ajax 請求
  301. //  大多數的 JavaScript 框架如 jquery,Mootools 等,在發出 Ajax 請求時,都會發送額外的 HTTP_X_REQUESTED_WITH 頭部信息,頭當他們一個ajax請求,因此你可以在服務器端偵測到 Ajax 請求。
  302. if(! emptyempty ( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && strtolower( $_SERVER['HTTP_X_REQUESTED_WITH'] ) == 'xmlhttprequest') {
  303. //If AJAX Request Then
  304. } else{
  305. //something else
  306. }
  307. ?>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章