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

原创
2016-06-21 08:51:07 674浏览

1. 发送短信

调用 TextMagic API。


  1. 		// Include the TextMagic PHP lib  
  2. require('textmagic-sms-api-php/TextMagicAPI.php');
  3. // Set the username and password information
  4. $username = 'myusername';
  5. $password = 'mypassword';
  6. // Create a new instance of TM
  7. $router = new TextMagicAPI(array(
  8. 'username' => $username,
  9. 'password' => $password
  10. ));
  11. // Send a text message to '999-123-4567'
  12. $result = $router->send('Wake up!', array(9991234567), true);
  13. // result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

2. 根据IP查找地址


  1. 		function detect_city($ip) {  
  2. $default = 'UNKNOWN';
  3. if (!is_string($ip) strlen($ip) < 1 $ip == '127.0.0.1' $ip == 'localhost')
  4. $ip = '8.8.8.8';
  5. $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)';
  6. $url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
  7. $ch = curl_init();
  8. $curl_opt = array(
  9. CURLOPT_FOLLOWLOCATION => 1,
  10. CURLOPT_HEADER => 0,
  11. CURLOPT_RETURNTRANSFER => 1,
  12. CURLOPT_USERAGENT => $curlopt_useragent,
  13. CURLOPT_URL => $url,
  14. CURLOPT_TIMEOUT => 1,
  15. CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
  16. );
  17. curl_setopt_array($ch, $curl_opt);
  18. $content = curl_exec($ch);
  19. if (!is_null($curl_info)) {
  20. $curl_info = curl_getinfo($ch);
  21. }
  22. curl_close($ch);
  23. if ( preg_match('{
  24. City : ([^<]*)
  25. }i', $content, $regs) ) {
  26. $city = $regs[1];
  27. }
  28. if ( preg_match('{
  29. State/Province : ([^<]*)
  30. }i', $content, $regs) ) {
  31. $state = $regs[1];
  32. }
  33. if( $city!='' && $state!='' ){
  34. $location = $city . ', ' . $state;
  35. return $location;
  36. }else{
  37. return $default;
  38. }
  39. }

3. 显示网页的源代码


  1. 		
    	
  2. $lines = file('http://google.com/');
  3. foreach ($lines as $line_num => $line) {
  4. // loop thru each line and prepend line numbers
  5. echo "Line #{$line_num} : " . htmlspecialchars($line) . "
    \n";
  6. }

4. 检查服务器是否使用HTTPS


  1. 		if ($_SERVER['HTTPS'] != "on") {  
  2. echo "This is not HTTPS";
  3. }else{
  4. echo "This is HTTPS";
  5. }

5. 显示Facebook粉丝数量


  1. 		function fb_fan_count($facebook_name){  
  2. // Example: https://graph.facebook.com/digimantra
  3. $data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
  4. echo $data->likes;
  5. }

6. 检测图片的主要颜色


  1. 		$i = imagecreatefromjpeg("image.jpg");  
  2. for ($x=0;$x
  3. for ($y=0;$y
  4. $rgb = imagecolorat($i,$x,$y);
  5. $r = ($rgb >> 16) & 0xFF;
  6. $g = ($rgb >> & 0xFF;
  7. $b = $rgb & 0xFF;
  8. $rTotal += $r;
  9. $gTotal += $g;
  10. $bTotal += $b;
  11. $total++;
  12. }
  13. }
  14. $rAverage = round($rTotal/$total);
  15. $gAverage = round($gTotal/$total);
  16. $bAverage = round($bTotal/$total);

7. 获取内存使用信息


  1. 		echo "Initial: ".memory_get_usage()." bytes \n";  
  2. /* prints
  3. Initial: 361400 bytes
  4. */
  5. // let's use up some memory
  6. for ($i = 0; $i < 100000; $i++) {
  7. $array []= md5($i);
  8. }
  9. // let's remove half of the array
  10. for ($i = 0; $i < 100000; $i++) {
  11. unset($array[$i]);
  12. }
  13. echo "Final: ".memory_get_usage()." bytes \n";
  14. /* prints
  15. Final: 885912 bytes
  16. */
  17. echo "Peak: ".memory_get_peak_usage()." bytes \n";
  18. /* prints
  19. Peak: 13687072 bytes
  20. */

8. 使用 gzcompress() 压缩数据


  1. 		$string =  
  2. "Lorem ipsum dolor sit amet, consectetur
  3. adipiscing elit. Nunc ut elit id mi ultricies
  4. adipiscing. Nulla facilisi. Praesent pulvinar,
  5. sapien vel feugiat vestibulum, nulla dui pretium orci,
  6. non ultricies elit lacus quis ante. Lorem ipsum dolor
  7. sit amet, consectetur adipiscing elit. Aliquam
  8. pretium ullamcorper urna quis iaculis. Etiam ac massa
  9. sed turpis tempor luctus. Curabitur sed nibh eu elit
  10. mollis congue. Praesent ipsum diam, consectetur vitae
  11. ornare a, aliquam a nunc. In id magna pellentesque
  12. tellus posuere adipiscing. Sed non mi metus, at lacinia
  13. augue. Sed magna nisi, ornare in mollis in, mollis
  14. sed nunc. Etiam at justo in leo congue mollis.
  15. Nullam in neque eget metus hendrerit scelerisque
  16. eu non enim. Ut malesuada lacus eu nulla bibendum
  17. id euismod urna sodales. ";
  18. $compressed = gzcompress($string);
  19. echo "Original size: ". strlen($string)."\n";
  20. /* prints
  21. Original size: 800
  22. */
  23. echo "Compressed size: ". strlen($compressed)."\n";
  24. /* prints
  25. Compressed size: 418
  26. */
  27. // getting it back
  28. $original = gzuncompress($compressed);

9. 使用PHP做Whois检查


  1. 		function whois_query($domain) {  
  2. // fix the domain name:
  3. $domain = strtolower(trim($domain));
  4. $domain = preg_replace('/^http:\/\//i', '', $domain);
  5. $domain = preg_replace('/^www\./i', '', $domain);
  6. $domain = explode('/', $domain);
  7. $domain = trim($domain[0]);
  8. // split the TLD from domain name
  9. $_domain = explode('.', $domain);
  10. $lst = count($_domain)-1;
  11. $ext = $_domain[$lst];
  12. // You find resources and lists
  13. // like these on wikipedia:
  14. //
  15. // http://de.wikipedia.org/wiki/Whois
  16. //
  17. $servers = array(
  18. "biz" => "whois.neulevel.biz",
  19. "com" => "whois.internic.net",
  20. "us" => "whois.nic.us",
  21. "coop" => "whois.nic.coop",
  22. "info" => "whois.nic.info",
  23. "name" => "whois.nic.name",
  24. "net" => "whois.internic.net",
  25. "gov" => "whois.nic.gov",
  26. "edu" => "whois.internic.net",
  27. "mil" => "rs.internic.net",
  28. "int" => "whois.iana.org",
  29. "ac" => "whois.nic.ac",
  30. "ae" => "whois.uaenic.ae",
  31. "at" => "whois.ripe.net",
  32. "au" => "whois.aunic.net",
  33. "be" => "whois.dns.be",
  34. "bg" => "whois.ripe.net",
  35. "br" => "whois.registro.br",
  36. "bz" => "whois.belizenic.bz",
  37. "ca" => "whois.cira.ca",
  38. "cc" => "whois.nic.cc",
  39. "ch" => "whois.nic.ch",
  40. "cl" => "whois.nic.cl",
  41. "cn" => "whois.cnnic.net.cn",
  42. "cz" => "whois.nic.cz",
  43. "de" => "whois.nic.de",
  44. "fr" => "whois.nic.fr",
  45. "hu" => "whois.nic.hu",
  46. "ie" => "whois.domainregistry.ie",
  47. "il" => "whois.isoc.org.il",
  48. "in" => "whois.ncst.ernet.in",
  49. "ir" => "whois.nic.ir",
  50. "mc" => "whois.ripe.net",
  51. "to" => "whois.tonic.to",
  52. "tv" => "whois.tv",
  53. "ru" => "whois.ripn.net",
  54. "org" => "whois.pir.org",
  55. "aero" => "whois.information.aero",
  56. "nl" => "whois.domain-registry.nl"
  57. );
  58. if (!isset($servers[$ext])){
  59. die('Error: No matching nic server found!');
  60. }
  61. $nic_server = $servers[$ext];
  62. $output = '';
  63. // connect to whois server:
  64. if ($conn = fsockopen ($nic_server, 43)) {
  65. fputs($conn, $domain."\r\n");
  66. while(!feof($conn)) {
  67. $output .= fgets($conn,128);
  68. }
  69. fclose($conn);
  70. }
  71. else { die('Error: Could not connect to ' . $nic_server . '!'); }
  72. return $output;
  73. }

10. 通过Email发送PHP错误


  1. 		
    	
  2. // Our custom error handler
  3. function nettuts_error_handler($number, $message, $file, $line, $vars){
  4. $email = "
  5. An error ($number) occurred on line

  6. $line and in the file: $file.
  7. $message

    ";
  8. $email .= "
    " . print_r($vars, 1) . "
    ";
  9. $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
  10. // Email the error to someone...
  11. error_log($email, 1, 'you@youremail.com', $headers);
  12. // Make sure that you decide how to respond to errors (on the user's side)
  13. // Either echo an error message, or kill the entire project. Up to you...
  14. // The code below ensures that we only "die" if the error was more than
  15. // just a NOTICE.
  16. if ( ($number !== E_NOTICE) && ($number < 2048) ) {
  17. die("There was an error. Please try again later.");
  18. }
  19. }
  20. // We should use our custom function to handle errors.
  21. set_error_handler('nettuts_error_handler');
  22. // Trigger an error... (var doesn't exist)
  23. echo $somevarthatdoesnotexist;



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。