当前位置:Gxlcms > PHP教程 > php获取外网真实IP的二种方法

php获取外网真实IP的二种方法

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

  1. function get_onlineip() {
  2. $ch = curl_init('http://www.ip138.com/ip2city.asp');
  3. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  4. $a = curl_exec($ch);
  5. preg_match('/\[(.*)\]/', $a, $ip);
  6. return $ip[1];
  7. }
  8. ?>

方法2:使用$_SERVER['HTTP_X_FORWARDED_FOR']

  1. function get_onlineip() {
  2. $onlineip = '';
  3. if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
  4. $onlineip = getenv('HTTP_CLIENT_IP');
  5. } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
  6. $onlineip = getenv('HTTP_X_FORWARDED_FOR');
  7. } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
  8. $onlineip = getenv('REMOTE_ADDR');
  9. } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
  10. $onlineip = $_SERVER['REMOTE_ADDR'];
  11. }
  12. return $onlineip;
  13. }
  14. ?>

人气教程排行