当前位置:Gxlcms > PHP教程 > php十个超级有用的PHP代码片段

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

时间:2021-07-01 10:21:17 帮助过:7人阅读

十个超级有用的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) < 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. 使用 gzcompress() 压缩数据
  112. $string =
  113. "Lorem ipsum dolor sit amet, consectetur
  114. adipiscing elit. Nunc ut elit id mi ultricies
  115. adipiscing. Nulla facilisi. Praesent pulvinar,
  116. sapien vel feugiat vestibulum, nulla dui pretium orci,
  117. non ultricies elit lacus quis ante. Lorem ipsum dolor
  118. sit amet, consectetur adipiscing elit. Aliquam
  119. pretium ullamcorper urna quis iaculis. Etiam ac massa
  120. sed turpis tempor luctus. Curabitur sed nibh eu elit
  121. mollis congue. Praesent ipsum diam, consectetur vitae
  122. ornare a, aliquam a nunc. In id magna pellentesque
  123. tellus posuere adipiscing. Sed non mi metus, at lacinia
  124. augue. Sed magna nisi, ornare in mollis in, mollis
  125. sed nunc. Etiam at justo in leo congue mollis.
  126. Nullam in neque eget metus hendrerit scelerisque
  127. eu non enim. Ut malesuada lacus eu nulla bibendum
  128. id euismod urna sodales. ";
  129. $compressed = gzcompress($string);
  130. echo "Original size: ". strlen($string)."\n";
  131. /* prints
  132. Original size: 800
  133. */
  134. echo "Compressed size: ". strlen($compressed)."\n";
  135. /* prints
  136. Compressed size: 418
  137. */
  138. // getting it back
  139. $original = gzuncompress($compressed);
  140. 9. 使用PHP做Whois检查
  141. function whois_query($domain) {
  142. // fix the domain name:
  143. $domain = strtolower(trim($domain));
  144. $domain = preg_replace('/^http:\/\//i', '', $domain);
  145. $domain = preg_replace('/^www\./i', '', $domain);
  146. $domain = explode('/', $domain);
  147. $domain = trim($domain[0]);
  148. // split the TLD from domain name
  149. $_domain = explode('.', $domain);
  150. $lst = count($_domain)-1;
  151. $ext = $_domain[$lst];
  152. // You find resources and lists
  153. // like these on wikipedia:
  154. //
  155. // http://de.wikipedia.org/wiki/Whois
  156. //
  157. $servers = array(
  158. "biz" => "whois.neulevel.biz",
  159. "com" => "whois.internic.net",
  160. "us" => "whois.nic.us",
  161. "coop" => "whois.nic.coop",
  162. "info" => "whois.nic.info",
  163. "name" => "whois.nic.name",
  164. "net" => "whois.internic.net",
  165. "gov" => "whois.nic.gov",
  166. "edu" => "whois.internic.net",
  167. "mil" => "rs.internic.net",
  168. "int" => "whois.iana.org",
  169. "ac" => "whois.nic.ac",
  170. "ae" => "whois.uaenic.ae",
  171. "at" => "whois.ripe.net",
  172. "au" => "whois.aunic.net",
  173. "be" => "whois.dns.be",
  174. "bg" => "whois.ripe.net",
  175. "br" => "whois.registro.br",
  176. "bz" => "whois.belizenic.bz",
  177. "ca" => "whois.cira.ca",
  178. "cc" => "whois.nic.cc",
  179. "ch" => "whois.nic.ch",
  180. "cl" => "whois.nic.cl",
  181. "cn" => "whois.cnnic.net.cn",
  182. "cz" => "whois.nic.cz",
  183. "de" => "whois.nic.de",
  184. "fr" => "whois.nic.fr",
  185. "hu" => "whois.nic.hu",
  186. "ie" => "whois.domainregistry.ie",
  187. "il" => "whois.isoc.org.il",
  188. "in" => "whois.ncst.ernet.in",
  189. "ir" => "whois.nic.ir",
  190. "mc" => "whois.ripe.net",
  191. "to" => "whois.tonic.to",
  192. "tv" => "whois.tv",
  193. "ru" => "whois.ripn.net",
  194. "org" => "whois.pir.org",
  195. "aero" => "whois.information.aero",
  196. "nl" => "whois.domain-registry.nl"
  197. );
  198. if (!isset($servers[$ext])){
  199. die('Error: No matching nic server found!');
  200. }
  201. $nic_server = $servers[$ext];
  202. $output = '';
  203. // connect to whois server:
  204. if ($conn = fsockopen ($nic_server, 43)) {
  205. fputs($conn, $domain."\r\n");
  206. while(!feof($conn)) {
  207. $output .= fgets($conn,128);
  208. }
  209. fclose($conn);
  210. }
  211. else { die('Error: Could not connect to ' . $nic_server . '!'); }
  212. return $output;
  213. }
  214. 10. 通过Email发送PHP错误
  215. // Our custom error handler
  216. function nettuts_error_handler($number, $message, $file, $line, $vars){
  217. $email = "
  218. An error ($number) occurred on line

  219. $line and in the file: $file.
  220. $message

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

人气教程排行