給大家分享21個常用的PHP函數程式碼段

WBOY
發布: 2016-07-25 09:08:31
原創
972 人瀏覽過
分享21個常用的PHP函數程式碼段
  1. 1. PHP可閱讀隨機字串
  2. 此程式碼將建立一個可閱讀的字串,使其更接近字典中的單字,實用且具有密碼驗證功能。
  3. /**************
  4. *@length –隨機字串的長度(必須是 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 – 隨機字串的長度
  23. */
  24. function generate_rand($l){
  25. $c= “ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz012345679XYZabcdefghijklmnopqrstuvwxyz012345679XYZabc 🎜>for($i=0; $i$rand.= $c[rand()%strlen($c)];
  26. }
  27. return $rand ;
  28. }
  29. 3. PHP編碼電子郵件地址
  30. 使用此程式碼,可以將任何電子郵件地址編碼為html 字元實體,以防止被垃圾郵件程式收集。
  31. function encode_email($email='info@domain.com', $linkText='Contact Us', $attrs ='class=”emailencoder」' )
  32. {
  33. // remplazar aroba y puntos
  34. $email = str_replace('@', '@', $email);
  35. $email = str_replace('.', '.', $email);
  36. $email = str_split( $email, 5);
  37. $linkText = str_replace('@', '@', $linkText);
  38. $linkText = str_replace('.', '.', $linkText);
  39. $linkText = str_split($linkText, 5);
  40. $part1 = '$part2 = 'ilto:';
  41. $part3 = '” '. $attrs .' >';
  42. $part4 = '';
  43. $encoded = '';
  44. return $encoded;
  45. }
  46. 4. PHP驗證郵件地址
  47. 電子郵件驗證也許是中最常用的網頁表單驗證,此程式碼除了驗證電子郵件地址,也可以選擇檢查郵件網域所屬DNS 中的MX 記錄,使郵件驗證功能更加強大。 ($email, $test_mx = false)
  48. {
  49. if(eregi(“^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a -z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$”, $email))
  50. if($test_mx)
  51. {
  52. list($username, $domain) = split(“@”, $email);
  53. return getmxrr($domain, $mxrecords);
  54. }
  55. else
  56. return true;
  57. else
  58. return false;
  59. }
  60. 5. PHP列出目錄內容
  61. function list_files($dir)
  62. {
  63. if(is_dir( $dir))
  64. {
  65. if($handle = opendir($dir))
  66. {
  67. while(($file = readdir($handle)) !== false)
  68. {
  69. if($file != “.” && $file != “..” && $file != “Thumbs.db”)
  70. {
  71. echo ''.$file.'
  72. '.”n”;
  73. }
  74. }
  75. closedir($handle);
  76. }
  77. }
  78. }
  79. 6. PHP銷毀目錄
  80. 刪除一個目錄,包括它的內容。
  81. /*****
  82. *@dir – 要銷毀的目錄
  83. *@virtual[可選]- 是否為虛擬目錄
  84. */
  85. function destroyDir($dir, $virtual = false)
  86. {
  87. $ds = DIRECTORY_SEPARATOR;
  88. {
  89. $ds = DIRECTORY_SEPARATOR;
  90. $dir = $virtual path ($dir) : $dir;
  91. $dir = substr($dir, -1) == $ds ? substr($dir, 0, -1) : $dir;
  92. if (is_dir($dir ) && $handle = opendir($dir))
  93. {
  94. while ($file = readdir($handle))
  95. {
  96. if ($file == '.' || $file = = '..')
  97. {
  98. continue;
  99. }
  100. elseif (is_dir($dir.$ds.$file))
  101. {
  102. destroyDir($dir.$ds .$file);
  103. }
  104. else
  105. {
  106. unlink($dir.$ds.$file);
  107. }
  108. }
  109. closedir($handle);
  110. rmdir($dir);
  111. return true;
  112. }
  113. else
  114. {
  115. return false;
  116. }
  117. }
  118. >return false;
  119. }
  120. }
  121. >>🎜>7
  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; //印出foo
  126. echo $obj->interest[1]; //印出php
  127. 8. PHP解析XML資料
  128. //xml字串
  129. $xml_string=”
  130. Foo
  131. foo@bar.com
  132. Foo
  133. foo@bar.com
  134. Foobar
  135. foobar@foo.com
  136. 」;
  137. //使用simplexml 載入xml 字串
  138. $xml = simplexml_load_string($xml_string); 🎜>//循環通過user的各個節點
  139. foreach ($xml->user as $user)
  140. {
  141. //存取屬性
  142. echo $user['id'], ' ';
  143. //子節點透過->存取運算子
  144. 回顯$使用者->姓名,'';
  145. 回顯$使用者->電子郵件,'
  146. ';
  147. }
  148. 9. PHP建立日誌縮寫
  149. 建立使用者友善的日誌縮寫。
  150. function create_slug($string){
  151. $slug=preg_replace('/[^A-Za- z0-9-]+/', '-', $string);
  152. 返回$slug;
  153. }
  154. 10. PHP取得客戶端真實IP位址
  155. 函數將取得使用者的真實IP位址,改為他使用代理伺服器。
  156. function getRealIpAddr()
  157. {
  158. if (!emptyempty ($_SERVER['HTTP_CLIENT_IP']))
  159. {
  160. $ip=$_SERVER]['IPTP_CLI] 🎜>}
  161. elseif (!emptyempty($_SERVER['HTTP_X_FORWARDED_FOR']))
  162. //檢查ip 是否從代理傳遞
  163. {
  164. $ip=$_SERVER['HTTP_X_FORD]; 🎜>}
  165. else
  166. {
  167. $ip=$_SERVER[ 'REMOTE_ADDR'];
  168. }
  169. 回傳$ip;
  170. }
  171. 111. PHP文件下載
  172. 提供使用者足夠的文件下載功能。
  173. /********************
  174. *@file – 檔案路徑
  175. */
  176. function force_download($file)
  177. {
  178. if ((isset($file))&&(file_exists($file))) {
  179. header(“內容長度:”.filesize($file));
  180. header('內容類型:應用程式/octet-stream');
  181. header('Content-Disposition:attachment; filename=” ' . $file . '”');
  182. readfile(“$file”);
  183. } else {
  184. 回顯「未選取檔案」;
  185. }
  186. }
  187. 12. PHP建立標籤雲
  188. function getCloud( $data = array(), $minFontSize = 12, $maxFontSize = 30 )
  189. {
  190. $minimumCount = min( array_values( $ ) );
  191. $maximumCount = max( array_values( $data ) );
  192. $spread = $maximumCount – $minimumCount;
  193. $cloudHTML = 」;
  194. $cloudTags = array(); >
  195. $spread == 0 && $spread = 1;
  196. foreach( $data as $tag => $count )
  197. {
  198. $size = $minFontSize + ( $count – $minimumCount )
  199. * ( $maxFontSize – $minFontSize ) / $spread;
  200. $cloudTags[] = '. '” href=”#” title=”” 。 $tag .
  201. ‘’ 回傳了 ‘ 的計數。 $計數。 ''>'
  202. 。 htmlspecialchars( stripslashes( $tag ) ) 。 '';
  203. }
  204. 返回 join(“n”, $cloudTags ) 。 「n」;
  205. }
  206. /************************
  207. **** 範例用法 ***/
  208. $arr = Array('Actionscript' => 35, 'Adobe' => 22, 'Array' => 44 , '背景' => 43,
  209. '模糊' => 18, '畫布' => 15, '調色板' => 11 ; 42,
  210. '分隔符號'=>13,'深度'=>34 ,'編碼'=>12,
  211. '提取' => 28,'過濾器' => 42);
  212. echo getCloud($arr, 12, 36);
  213. 13. PHP尋找兩個字串的相似性
  214. PHP提供了一個極少使用的similar_text函數,但這個函數非常有用,用於比較兩個字串並傳回相似的百分比。
  215. similar_text($string1, $string2, $percent);
  216. //$percent 將具有相似度百分比
  217. 14。 PHP 在應用程式中使用 Gravatar 通用頭像
  218. 隨著 WordPress 日益普及,Gravatar 也逐漸流行。由於 Gravatar 提供了易於使用的 API,將其納入應用程式也變得十分方便。
  219. /******************
  220. *@email – 顯示頭像的電子郵件地址
  221. *@size – 頭像大小
  222. *@default – 預設頭像的URL使用
  223. *@ rating – Gravatar 的評分(G, PG, R, X)
  224. */
  225. function show_gravatar($email, $size, $default, $ rating)
  226. {
  227. echo ''&default='.$default.' &size ='.$size.'&Rating='.$Rating.'" 寬度="'.$size.'px"
  228. 高度="'.$size.'px" />';
  229. }
  230. 15。字串。
  231. // Chirp Internet 的原始 PHP 程式碼:www.chirp.com.au
  232. // 請透過包含此標頭來確認此程式碼的使用。
  233. function myTruncate($string, $limit, $break=”.”, $pad=”...”) {
  234. // 如果字串短於$limit,則不做任何更改
  235. if(strlen($string) return $string;
  236. // $limit 與字串結尾之間是否存在$break?
  237. if(false !== ($breakpoint = strpos($string, $break, $limit) )) {
  238. if($breakpoint $string = substr($string, 0, $breakpoint) 。 $pad;
  239. }
  240. }
  241. return $string;
  242. }
  243. /***** 例 ****/
  244. $short_string=myTruncate($long_string, 100, ' ');
  245. 16。 PHP檔案Zip 壓縮
  246. /* 建立一個壓縮的zip 檔案*/
  247. function create_zip($files = array(),$destination = ”,$overwrite = false) {
  248. //如果zip 檔案已存在且覆寫為false,回傳false
  249. if(file_exists($destination) && !$overwrite) { return false; }
  250. //vars
  251. $valid_files = array();
  252. //如果檔案傳入...
  253. if(is_array($files)) {
  254. //循環遍歷每個檔案
  255. foreach($files as $file) {
  256. //確保文件存在
  257. if(file_exists($file)) {
  258. $valid_files[] = $file;
  259. }
  260. }
  261. }
  262. //如果我們有好的檔案…
  263. if(count($valid_files)) {
  264. //建立檔案
  265. $zip = new ZipArchive();
  266. if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
  267. return false;
  268. }
  269. //新增檔案
  270. foreach($valid_files as $file) {
  271. $zip->addFile($ file,$file);
  272. }
  273. //debug
  274. //echo 'zip 檔案包含',$zip->numFiles,' 狀態為',$zip->status;
  275. //關閉zip — 完成!
  276. {
  277. return false;
  278. }
  279. }
  280. /***** 用法範例 ***/
  281. $files=array('file1.jpg', 'file2.jpg', ' file3.gif');
  282. create_zip($files, 'myzipfile. zip', true);
  283. 17. PHP解壓縮Zip檔
  284. /**********************
  285. *@file – zip 檔案的路徑
  286. *@destination – 解壓縮檔案的目標目錄
  287. */
  288. function unzip_file($file, $destination){
  289. //建立物件
  290. $zip = new ZipArchive() ;
  291. // 開啟檔案
  292. if ($zip->open($ file) !== TRUE) {
  293. die ('無法開啟檔案');
  294. }
  295. //將內容提取到目標目錄
  296. $zip->extractTo($destination);
  297. //關閉存檔
  298. $zip->close();
  299. echo '存檔提取到目錄';
  300. }
  301. 18。 PHP為URL位址預設http字串
  302. 有時需要接受一些表單中的網址輸入,但使用者很少添加http://字段,此程式碼將為網址添加該字段。
  303. if (!preg_match(“/^(http|ftp):/”, $_POST['url'])) {
  304. $_POST['url'] = 'http://' .$_POST[' url'];
  305. }
  306. 19. PHP 將網址字串轉換成超級連結
  307. 此函數將URL 和電子郵件地址字串轉換為可點擊的超連結。
  308. function makeClickableLinks($text) {
  309. $text = eregi_replace('(((f|ht)lianqiangjavatp://)[-a-zA-Z0-9@:%_+.~ #?&//=]+)',
  310. '1 ', $text);
  311. $text = eregi_replace('([[:space:]()[{}])(www.[- a-zA-Z0-9@:%_+.~#? &//=]+)',
  312. '12', $text);
  313. $text = eregi_replace('([_.0 -9a-z-]+@([0-9a-z]) [0-9a-z-]+.)+[a-z]{2,3})',
  314. '1', $text) ;
  315. 回傳$text;
  316. }
  317. 20。 PHP 調整圖片
  318. 建立映像需要很多時間,此程式碼將有助於了解所需大小的邏輯。
  319. /**********************
  320. *@filename – 圖片路徑
  321. *@tmpname – 縮圖的暫時路徑
  322. *@xmax – 最大值寬度
  323. *@ymax – 最大高度
  324. */
  325. function resize_image( $filename, $tmpname, $xmax, $ymax)
  326. {
  327. $ext =explode(“.”, $filename );
  328. $ext = $ext[count($ext)-1];
  329. if($ext == “jpg” || $ext == “jpeg”)
  330. $im = imagecreatefromjpeg($tmpname);
  331. elseif($ext == “png”)
  332. $im = imagecreatefrompng($tmpname);
  333. elseif($ext == “gif”)
  334. $im🎜>elseif($ext == “gif”)
  335. $im🎜>$im = imagecreatefromgif($tmpname);
  336. $x = imagesx($im );
  337. $y = imagesy($im);
  338. if($x return $im;
  339. if($x >= $y) {
  340. $newx = $xmax;
  341. $newy = $newx * $y / $x;
  342. }
  343. else {
  344. $newy = $ymax;
  345. $newx = $x / $y * $newy;
  346. }
  347. $im2 = imagecreatetruecolorcolor ($newx, $newy);
  348. imagecopyresized($im2, $ im, 0, 0, 0, 0, 樓層($newx), 樓層($newy), $x, $y);
  349. 返回$im2;
  350. }
  351. 21. PHP偵測ajax請求
  352. 大部分的JavaScript框架如jquery,Mootools等,在發出Ajax請求時,都會發送額外的HTTP_X_REQUESTED_WITHTHTHi ,當一個ajax請求時,你可以在伺服器端監聽測到Ajax 請求。
  353. if(!emptyempty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
  354. /如果是AJV🎜> }其他{
  355. //其他
  356. }
  357. 複製程式碼


來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!