十个超级有用的PHP代码片段

  1. 1. 发送短信  调用 TextMagic API。  
  2. <?php  
  3. // Include the TextMagic PHP lib  
  4. require('textmagic-sms-api-php/TextMagicAPI.php');  
  5.   
  6. // Set the username and password information  
  7. $username = 'myusername';  
  8. $password = 'mypassword';  
  9.   
  10. // Create a new instance of TM  
  11. $router = new TextMagicAPI(array(  
  12. 'username' => $username,  
  13. 'password' => $password  
  14. ));  
  15.   
  16. // Send a text message to '999-123-4567'  
  17. $result = $router->send('Wake up!'array(9991234567), true);  
  18.   
  19. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )  
  20.   
  21. ?>  
  22.   
  23.   
  24.   
  25.   
  26. 2. 根据IP查找地址  
  27. <?php  
  28. function detect_city($ip) {  
  29.   
  30. $default = 'UNKNOWN';  
  31.   
  32. if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')  
  33. $ip = '8.8.8.8';  
  34.   
  35. $curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';  
  36.   
  37. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);  
  38. $ch = curl_init();  
  39.   
  40. $curl_opt = array(  
  41. CURLOPT_FOLLOWLOCATION => 1,  
  42. CURLOPT_HEADER => 0,  
  43. CURLOPT_RETURNTRANSFER => 1,  
  44. CURLOPT_USERAGENT => $curlopt_useragent,  
  45. CURLOPT_URL => $url,  
  46. CURLOPT_TIMEOUT => 1,  
  47. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],  
  48. );  
  49.   
  50. curl_setopt_array($ch$curl_opt);  
  51.   
  52. $content = curl_exec($ch);  
  53.   
  54. if (!is_null($curl_info)) {  
  55. $curl_info = curl_getinfo($ch);  
  56. }  
  57.   
  58. curl_close($ch);  
  59.   
  60. if ( preg_match('{<li>City : ([^<]*)</li>}i'$content$regs) ) {  
  61. $city = $regs[1];  
  62. }  
  63. if ( preg_match('{<li>State/Province : ([^<]*)</li>}i'$content$regs) ) {  
  64. $state = $regs[1];  
  65. }  
  66.   
  67. if$city!='' && $state!='' ){  
  68. $location = $city . ', ' . $state;  
  69. return$location;  
  70. }else{  
  71. return$default;  
  72. }  
  73.   
  74. }  
  75. ?>  
  76.   
  77. 3. 显示网页的源代码  
  78.   
  79. <?php   
  80. // display source code  
  81. $lines = file('http://google.com/');  
  82. foreach ($lines as $line_num => $line) {  
  83. // loop thru each line and prepend line numbers  
  84. echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";  
  85. }  
  86. ?>  
  87.   
  88. 4. 检查服务器是否使用HTTPS  
  89. <?php  
  90. if ($_SERVER['HTTPS'] != "on") {  
  91. echo "This is not HTTPS";  
  92. }else{  
  93. echo "This is HTTPS";  
  94. }  
  95. ?>  
  96.   
  97. 5. 显示Faceboo**丝数量  
  98. <?php  
  99. function fb_fan_count($facebook_name){  
  100. // Example: https://graph.facebook.com/digimantra  
  101. $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));  
  102. echo $data->likes;  
  103. }  
  104. ?>  
  105.   
  106. 6. 检测图片的主要颜色  
  107. <?php  
  108. $i = imagecreatefromjpeg("image.jpg");  
  109.   
  110. for ($x=0;$x<imagesx($i);$x++) {  
  111. for ($y=0;$y<imagesy($i);$y++) {  
  112. $rgb = imagecolorat($i,$x,$y);  
  113. $r = ($rgb >> 16) & 0xFF;  
  114. $g = ($rgb >> & 0xFF;  
  115. $b = $rgb & 0xFF;  
  116.   
  117. $rTotal += $r;  
  118. $gTotal += $g;  
  119. $bTotal += $b;  
  120. $total++;  
  121. }  
  122. }  
  123.   
  124. $rAverage = round($rTotal/$total);  
  125. $gAverage = round($gTotal/$total);  
  126. $bAverage = round($bTotal/$total);  
  127. ?>  
  128.   
  129. 7. 获取内存使用信息  
  130.   
  131. <?php  
  132. echo"Initial: ".memory_get_usage()." bytes \n";  
  133. /* prints 
  134. Initial: 361400 bytes 
  135. */  
  136. // http://www.baoluowanxiang.com/  
  137. // let's use up some memory  
  138. for ($i = 0; $i < 100000; $i++) {  
  139. $array []= md5($i);  
  140. }  
  141.   
  142. // let's remove half of the array  
  143. for ($i = 0; $i < 100000; $i++) {  
  144. unset($array[$i]);  
  145. }  
  146.   
  147. echo"Final: ".memory_get_usage()." bytes \n";  
  148. /* prints 
  149. Final: 885912 bytes 
  150. */  
  151.   
  152. echo"Peak: ".memory_get_peak_usage()." bytes \n";  
  153. /* prints 
  154. Peak: 13687072 bytes 
  155. */  
  156. ?>  
  157.   
  158.   
  159. 8. 使用 gzcompress() 压缩数据  
  160. <?php  
  161. $string =  
  162. "Lorem ipsum dolor sit amet, consectetur  
  163. adipiscing elit. Nunc ut elit id mi ultricies  
  164. adipiscing. Nulla facilisi. Praesent pulvinar,  
  165. sapien vel feugiat vestibulum, nulla dui pretium orci,  
  166. non ultricies elit lacus quis ante. Lorem ipsum dolor  
  167. sit amet, consectetur adipiscing elit. Aliquam  
  168. pretium ullamcorper urna quis iaculis. Etiam ac massa  
  169. sed turpis tempor luctus. Curabitur sed nibh eu elit  
  170. mollis congue. Praesent ipsum diam, consectetur vitae  
  171. ornare a, aliquam a nunc. In id magna pellentesque  
  172. tellus posuere adipiscing. Sed non mi metus, at lacinia  
  173. augue. Sed magna nisi, ornare in mollis in, mollis  
  174. sed nunc. Etiam at justo in leo congue mollis.  
  175. Nullam in neque eget metus hendrerit scelerisque  
  176. eu non enim. Ut malesuada lacus eu nulla bibendum  
  177. id euismod urna sodales. ";  
  178.   
  179. $compressed = gzcompress($string);  
  180.   
  181. echo "Original size: "strlen($string)."\n";  
  182. /* prints 
  183. Original size: 800 
  184. */  
  185.   
  186. echo "Compressed size: "strlen($compressed)."\n";  
  187. /* prints 
  188. Compressed size: 418 
  189. */  
  190.   
  191. // getting it back  
  192. $original = gzuncompress($compressed);  
  193. ?>  
  194.   
  195. 9. 使用PHP做Whois检查  
  196.   
  197. <?php  
  198. function whois_query($domain) {  
  199.   
  200. // fix the domain name:  
  201. $domain = strtolower(trim($domain));  
  202. $domain = preg_replace('/^http:\/\//i'''$domain);  
  203. $domain = preg_replace('/^www\./i'''$domain);  
  204. $domain = explode('/'$domain);  
  205. $domain = trim($domain[0]);  
  206.   
  207. // split the TLD from domain name  
  208. $_domain = explode('.'$domain);  
  209. $lst = count($_domain)-1;  
  210. $ext = $_domain[$lst];  
  211.   
  212. // You find resources and lists  
  213. // like these on wikipedia:  
  214. //  
  215. // http://de.wikipedia.org/wiki/Whois  
  216. //  
  217. $servers = array(  
  218. "biz" => "whois.neulevel.biz",  
  219. "com" => "whois.internic.net",  
  220. "us" => "whois.nic.us",  
  221. "coop" => "whois.nic.coop",  
  222. "info" => "whois.nic.info",  
  223. "name" => "whois.nic.name",  
  224. "net" => "whois.internic.net",  
  225. "gov" => "whois.nic.gov",  
  226. "edu" => "whois.internic.net",  
  227. "mil" => "rs.internic.net",  
  228. "int" => "whois.iana.org",  
  229. "ac" => "whois.nic.ac",  
  230. "ae" => "whois.uaenic.ae",  
  231. "at" => "whois.ripe.net",  
  232. "au" => "whois.aunic.net",  
  233. "be" => "whois.dns.be",  
  234. "bg" => "whois.ripe.net",  
  235. "br" => "whois.registro.br",  
  236. "bz" => "whois.belizenic.bz",  
  237. "ca" => "whois.cira.ca",  
  238. "cc" => "whois.nic.cc",  
  239. "ch" => "whois.nic.ch",  
  240. "cl" => "whois.nic.cl",  
  241. "cn" => "whois.cnnic.net.cn",  
  242. "cz" => "whois.nic.cz",  
  243. "de" => "whois.nic.de",  
  244. "fr" => "whois.nic.fr",  
  245. "hu" => "whois.nic.hu",  
  246. "ie" => "whois.domainregistry.ie",  
  247. "il" => "whois.isoc.org.il",  
  248. "in" => "whois.ncst.ernet.in",  
  249. "ir" => "whois.nic.ir",  
  250. "mc" => "whois.ripe.net",  
  251. "to" => "whois.tonic.to",  
  252. "tv" => "whois.tv",  
  253. "ru" => "whois.ripn.net",  
  254. "org" => "whois.pir.org",  
  255. "aero" => "whois.information.aero",  
  256. "nl" => "whois.domain-registry.nl"  
  257. );  
  258.   
  259. if (!isset($servers[$ext])){  
  260. die('Error: No matching nic server found!');  
  261. }  
  262.   
  263. $nic_server = $servers[$ext];  
  264.   
  265. $output = '';  
  266.   
  267. // connect to whois server:  
  268. if ($conn = fsockopen ($nic_server, 43)) {  
  269. fputs($conn$domain."\r\n");  
  270. while(!feof($conn)) {  
  271. $output .= fgets($conn,128);  
  272. }  
  273. fclose($conn);  
  274. }  
  275. else { die('Error: Could not connect to ' . $nic_server . '!'); }  
  276.   
  277. return $output;  
  278. }  
  279. ?>  
  280.   
  281. 10. 通过Email发送PHP错误  
  282.   
  283. <?php  
  284.   
  285. // Our custom error handler  
  286. function nettuts_error_handler($number$message$file$line$vars){  
  287. $email = "  
  288. <p>An error ($number) occurred on line  
  289. <strong>$line</strong> and in the <strong>file: $file.</strong>  
  290. <p> $message </p>";  
  291.   
  292. $email .= "<pre>" . print_r($vars, 1) . "</pre>";  
  293.   
  294. $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";  
  295.   
  296. // Email the error to someone...  
  297. error_log($email, 1, 'you@youremail.com'$headers);  
  298.   
  299. // Make sure that you decide how to respond to errors (on the user's side)  
  300. // Either echo an error message, or kill the entire project. Up to you...  
  301. // The code below ensures that we only "die" if the error was more than  
  302. // just a NOTICE.  
  303. if ( ($number !== E_NOTICE) && ($number < 2048) ) {  
  304. die("There was an error. Please try again later.");  
  305. }  
  306. }  
  307.   
  308. // We should use our custom function to handle errors.  
  309. set_error_handler('nettuts_error_handler');  
  310.   
  311. // Trigger an error... (var doesn't exist)  
  312. echo$somevarthatdoesnotexist;  
  313. ?> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值