php Ten super useful PHP code snippets

WBOY
Release: 2016-07-25 08:42:07
Original
1031 people have browsed it

Ten super useful php code snippets

[PHP] code

  1. 1. Send SMS
  2. Call TextMagic API.
  3. // Include the TextMagic PHP lib
  4. require('textmagic-sms-api-php/TextMagicAPI.php');
  5. // Set the username and password information
  6. $username = 'myusername';
  7. $password = 'mypassword';
  8. // Create a new instance of TM
  9. $router = new TextMagicAPI(array(
  10. 'username' => $username,
  11. 'password' => $password
  12. ));
  13. // Send a text message to '999-123-4567'
  14. $result = $router->send('Wake up!', array(9991234567), true);
  15. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )
  16. 2. 根据IP查找地址
  17. function detect_city($ip) {
  18. $default = 'UNKNOWN';
  19. if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost')
  20. $ip = '8.8.8.8';
  21. $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)';
  22. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
  23. $ch = curl_init();
  24. $curl_opt = array(
  25. CURLOPT_FOLLOWLOCATION => 1,
  26. CURLOPT_HEADER => 0,
  27. CURLOPT_RETURNTRANSFER => 1,
  28. CURLOPT_USERAGENT => $curlopt_useragent,
  29. CURLOPT_URL => $url,
  30. CURLOPT_TIMEOUT => 1,
  31. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  32. );
  33. curl_setopt_array($ch, $curl_opt);
  34. $content = curl_exec($ch);
  35. if (!is_null($curl_info)) {
  36. $curl_info = curl_getinfo($ch);
  37. }
  38. curl_close($ch);
  39. if ( preg_match('{
  40. City : ([^<]*)
  41. }i', $content, $regs) ) {
  42. $city = $regs[1];
  43. }
  44. if ( preg_match('{
  45. State/Province : ([^<]*)
  46. }i', $content, $regs) ) {
  47. $state = $regs[1];
  48. }
  49. if( $city!='' && $state!='' ){
  50. $location = $city . ', ' . $state;
  51. return$location;
  52. }else{
  53. return$default;
  54. }
  55. }
  56. 3. 显示网页的源代码
  57. $lines = file('http://google.com/');
  58. foreach ($lines as $line_num => $line) {
  59. // loop thru each line and prepend line numbers
  60. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    n";
  61. }
  62. 4. 检查服务器是否使用HTTPS
  63. if ($_SERVER['HTTPS'] != "on") {
  64. echo "This is not HTTPS";
  65. }else{
  66. echo "This is HTTPS";
  67. }
  68. 5. 显示Faceboo**丝数量
  69. function fb_fan_count($facebook_name){
  70. // Example: https://graph.facebook.com/digimantra
  71. $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
  72. echo $data->likes;
  73. }
  74. 6. 检测图片的主要颜色
  75. $i = imagecreatefromjpeg("image.jpg");
  76. for ($x=0;$xfor ($y=0;$y$rgb = imagecolorat($i,$x,$y);
  77. $r = ($rgb >> 16) & 0xFF;
  78. $g = ($rgb >> & 0xFF;
  79. $b = $rgb & 0xFF;
  80. $rTotal += $r;
  81. $gTotal += $g;
  82. $bTotal += $b;
  83. $total++;
  84. }
  85. }
  86. $rAverage = round($rTotal/$total);
  87. $gAverage = round($gTotal/$total);
  88. $bAverage = round($bTotal/$total);
  89. 7. 获取内存使用信息
  90. echo"Initial: ".memory_get_usage()." bytes n";
  91. /* prints
  92. Initial: 361400 bytes
  93. */
  94. // http://www.baoluowanxiang.com/
  95. // let's use up some memory
  96. for ($i = 0; $i < 100000; $i++) {
  97. $array []= md5($i);
  98. }
  99. // let's remove half of the array
  100. for ($i = 0; $i < 100000; $i++) {
  101. unset($array[$i]);
  102. }
  103. echo"Final: ".memory_get_usage()." bytes n";
  104. /* prints
  105. Final: 885912 bytes
  106. */
  107. echo"Peak: ".memory_get_peak_usage()." bytes n";
  108. /* prints
  109. Peak: 13687072 bytes
  110. */
  111. 8. Use gzcompress() to compress data
  112. $string =
  113. "The pain itself should be real, it will be followed
  114. adipiscing elit. Now as elit it my ultricies
  115. adipiscing. No facilisi. Praesent pulvinar,
  116. sapien or feugiat vestibulum, no dui price orci,
  117. not ultricies lacus
  118. sit amet adipiscing
  119. the price of ullamcorper
  120. sed turpis
  121. to decorate a now
  122. Nullam in neque methres hendrerit
  123. eu no for. Ut malesuada lacus nulla drinkum
  124. id euismod urna. ";
  125. $compressed = gzcompress($string);
  126. echo "Original size: ". strlen($string)."n";
  127. /* prints
  128. Original size: 800
  129. */
  130. echo "Compressed size: ". strlen($compressed)."n";
  131. /* prints
  132. Compressed size: 418
  133. */
  134. // getting it back
  135. $original = gzuncompress($compressed);
  136. 9. Using PHP 做Whois 免费
  137. function whois_query($domain) {
  138. // fix the domain name:
  139. $domain = strtolower(trim($domain));
  140. $domain = preg_replace('/^http:/// i', '', $domain);
  141. $domain = preg_replace('/^www./i', '', $domain);
  142. $domain = explode('/', $domain);
  143. $domain = trim($domain[0]);
  144. // split the TLD from domain name
  145. $_domain = explode('.', $domain);
  146. $lst = count($_domain)-1;
  147. $ext = $ _domain[$lst];
  148. // You find resources and lists
  149. // like these on wikipedia:
  150. //
  151. // http://de.wikipedia.org/wiki/Whois
  152. //
  153. $servers = array (
  154. "biz" => "whois.neulevel.biz",
  155. "com" => "whois.internic.net",
  156. "us" => "whois.nic.us",
  157. "coop" => "whois.nic.coop" => "whois.nic.name" => "whois.nic.name" => .internic.net",
  158. "gov" => "whois.nic.gov",
  159. "edu" => "whois.internic.net",
  160. "mil" => "rs.internic.net" ,
  161. "int" => "whois.iana.org",
  162. "ac" => "whois.uaenic.ae" => "whois.ripe.net",
  163. "au" => "whois.aunic.net" => "whois.dns.be" => "whois.ripe.net",
  164. "br" => "whois.registro.br",
  165. "bz" => "whois.belizenic.bz",
  166. "ca" => "whois.cira.ca",
  167. "cc" => "whois.nic.cc",
  168. "ch" => "whois.nic.ch",
  169. "cl" => "whois.nic.cl",
  170. "cn" => "whois.cnnic.net.cn",
  171. "cz" => "whois.nic.cz",
  172. "de" => "whois.nic.de",
  173. "fr" => "whois.nic.fr",
  174. "hu" => "whois.nic.hu",
  175. "ie" => "whois.domainregistry.ie",
  176. "il" => "whois.isoc.org.il",
  177. "in" => "whois.ncst.ernet.in",
  178. "ir" => "whois.nic.ir",
  179. "mc" => "whois.ripe.net",
  180. "to" => "whois.tonic.to",
  181. "tv" => "whois.tv",
  182. "ru" => "whois.ripn.net",
  183. "org" => "whois.pir.org",
  184. "aero" => "whois.information.aero",
  185. "nl" => "whois.domain-registry.nl"
  186. );
  187. if (!isset($servers[$ext])){
  188. die('Error: No matching nic server found!');
  189. }
  190. $nic_server = $servers[$ext];
  191. $output = '';
  192. // connect to whois server:
  193. if ($conn = fsockopen ($nic_server, 43)) {
  194. fputs($conn, $domain."rn ");
  195. while(!feof($conn)) {
  196. $output .= fgets($conn,128);
  197. }
  198. fclose($conn);
  199. }
  200. else { die('Error: Could not connect to ' . $nic_server '!'); }
  201. return $output;
  202. }
  203. 10. 通过Email发送PHP错误
  204. // Our custom error handler
  205. function nettuts_error_handler($number, $message, $file, $line, $vars){
  206. $email = "
  207. An error ($number) occurred on line

  208. $line and in the file: $file.
  209. $message

    ";
  210. $email .= "
    " . print_r($vars, 1) . "
    ";
  211. $headers = 'Content-type: text/html; charset=iso-8859-1' . "rn";
  212. // Email the error to someone...
  213. error_log($email, 1, 'you@youremail.com', $headers);
  214. // Make sure that you decide how to respond to errors (on the user's side)
  215. // Either echo an error message, or kill the entire project. Up to you...
  216. // The code below ensures that we only "die" if the error was more than
  217. // just a NOTICE.
  218. if ( ($number !== E_NOTICE) && ($number < 2048) ) {
  219. die("There was an error. Please try again later.");
  220. }
  221. }
  222. // We should use our custom function to handle errors.
  223. set_error_handler('nettuts_error_handler');
  224. // Trigger an error... (var doesn't exist)
  225. echo$somevarthatdoesnotexist;
复制代码
php, PHP


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template