十個超級有用的PHP代碼片段
1.發送簡訊
調用 TextMagic API。
<?phpn// Include the TextMagic PHP lib nrequire(textmagic-sms-api-php/TextMagicAPI.php); nn// Set the username and password information n$username = myusername; n$password = mypassword; n// Create a new instance of TM n$router = new TextMagicAPI(array( nusername => $username, npassword => $password n)); nn// Send a text message to 999-123-4567 n$result = $router->send(Wake up!, array(9991234567), true); nn// result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 ) n
2. 根據IP查找地址
<?phpnfunction detect_city($ip) { n$default = UNKNOWN; nif (!is_string($ip) || strlen($ip) < 1 || $ip == 127.0.0.1 || $ip == localhost) n $ip = 8.8.8.8; n$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); n$url = http://ipinfodb.com/ip_locator.php?ip= . urlencode($ip); n$ch = curl_init(); n$curl_opt = array( n CURLOPT_FOLLOWLOCATION => 1, n CURLOPT_HEADER => 0, n CURLOPT_RETURNTRANSFER => 1, n CURLOPT_USERAGENT => $curlopt_useragent, n CURLOPT_URL => $url, n CURLOPT_TIMEOUT => 1, n CURLOPT_REFERER => http:// . $_SERVER[HTTP_HOST], n); ncurl_setopt_array($ch, $curl_opt); n$content = curl_exec($ch); nif (!is_null($curl_info)) { n $curl_info = curl_getinfo($ch); n} ncurl_close($ch); nif ( preg_match({<li>City : ([^<]*)</li>}i, $content, $regs) ) { n $city = $regs[1]; n} nif ( preg_match({<li>State/Province : ([^<]*)</li>}i, $content, $regs) ) { n $state = $regs[1]; n} nif( $city!= && $state!= ){ n $location = $city . , . $state; n return $location; n}else{ n return $default; n} n} n
3. 顯示網頁的源代碼
<?php n// display source code n$lines = file(http://google.com/); nforeach ($lines as $line_num => $line) { n // loop thru each line and prepend line numbers n echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>n"; n} n
4. 檢查伺服器是否使用HTTPS
<?phpnif ($_SERVER[HTTPS] != "on") { necho "This is not HTTPS"; n}else{ necho "This is HTTPS"; n} n
5. 顯示Facebook粉絲數量
<?phpnfunction fb_fan_count($facebook_name){ n// Example: https://graph.facebook.com/digimantra n$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name)); necho $data->likes; n} n
6. 檢測圖片的主要顏色
<?phpn$i = imagecreatefromjpeg("image.jpg"); nfor ($x=0;$x<imagesx($i);$x++) { nfor ($y=0;$y<imagesy($i);$y++) { n$rgb = imagecolorat($i,$x,$y); n$r = ($rgb >> 16) & 0xFF; n$g = ($rgb >> & 0xFF; n$b = $rgb & 0xFF; nn$rTotal += $r; n$gTotal += $g; n$bTotal += $b; n$total++; n} n} n$rAverage = round($rTotal/$total); n$gAverage = round($gTotal/$total); n$bAverage = round($bTotal/$total); n
7. 獲取內存使用信息
<?phpnecho "Initial: ".memory_get_usage()." bytes n"; n/* prints nInitial: 361400 bytes n*/ nn// lets use up some memory nfor ($i = 0; $i < 100000; $i++) { n$array []= md5($i); n} nn// lets remove half of the array nfor ($i = 0; $i < 100000; $i++) { nunset($array[$i]); n} nnecho "Final: ".memory_get_usage()." bytes n"; n/* prints nFinal: 885912 bytes n*/ nnecho "Peak: ".memory_get_peak_usage()." bytes n"; n/* prints nPeak: 13687072 bytes n*/ n
8. 使用 gzcompress() 壓縮數據
<?phpn$string = n"Lorem ipsum dolor sit amet, consectetur nadipiscing elit. Nunc ut elit id mi ultricies nadipiscing. Nulla facilisi. Praesent pulvinar, nsapien vel feugiat vestibulum, nulla dui pretium orci, nnon ultricies elit lacus quis ante. Lorem ipsum dolor nsit amet, consectetur adipiscing elit. Aliquam npretium ullamcorper urna quis iaculis. Etiam ac massa nsed turpis tempor luctus. Curabitur sed nibh eu elit nmollis congue. Praesent ipsum diam, consectetur vitae nornare a, aliquam a nunc. In id magna pellentesque ntellus posuere adipiscing. Sed non mi metus, at lacinia naugue. Sed magna nisi, ornare in mollis in, mollis nsed nunc. Etiam at justo in leo congue mollis. nNullam in neque eget metus hendrerit scelerisque neu non enim. Ut malesuada lacus eu nulla bibendum nid euismod urna sodales. "; nn$compressed = gzcompress($string); nnecho "Original size: ". strlen($string)."n"; n/* prints nOriginal size: 800 n*/ nnecho "Compressed size: ". strlen($compressed)."n"; n/* prints nCompressed size: 418 n*/ nn// getting it back n$original = gzuncompress($compressed); n
9. 使用PHP做Whois檢查
<?phpnfunction whois_query($domain) { n// fix the domain name: n$domain = strtolower(trim($domain)); n$domain = preg_replace(/^http:///i, , $domain); n$domain = preg_replace(/^www./i, , $domain); n$domain = explode(/, $domain); n$domain = trim($domain[0]); nn// split the TLD from domain name n$_domain = explode(., $domain); n$lst = count($_domain)-1; n$ext = $_domain[$lst]; nn// You find resources and lists n// like these on wikipedia: n// n// http://de.wikipedia.org/wiki/Whois n// n$servers = array( n"biz" => "whois.neulevel.biz", n"com" => "whois.internic.net", n"us" => "whois.nic.us", n"coop" => "whois.nic.coop", n"info" => "whois.nic.info", n"name" => "whois.nic.name", n"net" => "whois.internic.net", n"gov" => "whois.nic.gov", n"edu" => "whois.internic.net", n"mil" => "rs.internic.net", n"int" => "whois.iana.org", n"ac" => "whois.nic.ac", n"ae" => "whois.uaenic.ae", n"at" => "whois.ripe.net", n"au" => "whois.aunic.net", n"be" => "whois.dns.be", n"bg" => "whois.ripe.net", n"br" => "whois.registro.br", n"bz" => "whois.belizenic.bz", n"ca" => "whois.cira.ca", n"cc" => "whois.nic.cc", n"ch" => "whois.nic.ch", n"cl" => "whois.nic.cl", n"cn" => "whois.cnnic.net.cn", n"cz" => "whois.nic.cz", n"de" => "whois.nic.de", n"fr" => "whois.nic.fr", n"hu" => "whois.nic.hu", n"ie" => "whois.domainregistry.ie", n"il" => "whois.isoc.org.il", n"in" => "whois.ncst.ernet.in", n"ir" => "whois.nic.ir", n"mc" => "whois.ripe.net", n"to" => "whois.tonic.to", n"tv" => "whois.tv", n"ru" => "whois.ripn.net", n"org" => "whois.pir.org", n"aero" => "whois.information.aero", n"nl" => "whois.domain-registry.nl" n); nnif (!isset($servers[$ext])){ ndie(Error: No matching nic server found!); n} nn$nic_server = $servers[$ext]; nn$output = ; nn// connect to whois server: nif ($conn = fsockopen ($nic_server, 43)) { nfputs($conn, $domain."rn"); nwhile(!feof($conn)) { n $output .= fgets($conn,128); n} nfclose($conn); n} nelse { die(Error: Could not connect to . $nic_server . !); } nnreturn $output; n} n
10. 通過Email發送PHP錯誤
<?php n// Our custom error handler nfunction nettuts_error_handler($number, $message, $file, $line, $vars){ n$email = " n<p>An error ($number) occurred on line n<strong>$line</strong> and in the <strong>file: $file.</strong> n<p> $message </p>"; nn$email .= "<pre>" . print_r($vars, 1) . "</pre>"; nn$headers = Content-type: text/html; charset=iso-8859-1 . "rn"; nn// Email the error to someone... nerror_log($email, 1, you@youremail.com, $headers); nn// Make sure that you decide how to respond to errors (on the users side) n// Either echo an error message, or kill the entire project. Up to you... n// The code below ensures that we only "die" if the error was more than n// just a NOTICE. nif ( ($number !== E_NOTICE) && ($number < 2048) ) { ndie("There was an error. Please try again later."); n} n} nn// We should use our custom function to handle errors. nset_error_handler(nettuts_error_handler); nn// Trigger an error... (var doesnt exist) necho $somevarthatdoesnotexist; n
推薦閱讀:
※PHP開發微博,需要注意哪些問題?或者是需要用到哪些技術便於開發?
※前端工程師學 Node.js 好還是 PHP 好?
※給PHPStorm染上Material 主題
※大逃殺?BR大逃殺!
※如何評價PHP7 Alpha 1?
TAG:PHP |