欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2022-04-28 20:11:09
...

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

[PHP]代码

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

  214. $line and in the file: $file.
  215. $message

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