Home >Backend Development >PHP Tutorial >Two ways to get the real IP of the external network in php

Two ways to get the real IP of the external network in php

WBOY
WBOYOriginal
2016-07-25 09:04:112665browse
  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. ?>
复制代码


Statement:
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
Previous article:php code to upload imagesNext article:php code to upload images