PHP access to the local network/public network IP code _php skills

Source: Internet
Author: User
We generally use $_server[' remote_addr ' to get User IP,

However, if the reverse proxy is used, the REMOTE_ADDR in the HTTP header is not the user's address, but the address of the agent at the top level.

After my research there are two ways to get the user's real extranet IP.


Method One: Curl
Copy Code code as follows:

function Get_onlineip () {
$ch = Curl_init (' http://www.ip138.com/ip2city.asp ');
curl_setopt ($ch, Curlopt_returntransfer, true);
$a = curl_exec ($ch);
Preg_match ('/\[(. *) \]/', $a, $ip);
return $IP [1];
}



Method Two: $_server[' http_x_forwarded_for ' to obtain the corresponding address
Copy Code code as follows:

function Get_onlineip () {
$onlineip = ';
if (getenv (' http_client_ip ') && strcasecmp (getenv (' http_client_ip '), ' unknown ') {
$onlineip = getenv ( ' Http_client_ip ');
} elseif (getenv (' http_x_forwarded_for ') && strcasecmp (getenv (' http_x_forwarded_for '), ' unknown ')) {
$onlineip = getenv (' http_x_forwarded_for ');
} elseif (getenv (' remote_addr ') && strcasecmp (getenv (' remote_addr '), ' unknown ')) {
$onlineip = getenv (' Remote_addr ');
} elseif (Isset ($_server[' remote_addr ']) && $_server[' remote_addr '] && strcasecmp ($_server[' Remote_addr '], ' unknown ') {
$onlineip = $_server[' remote_addr '];
}
Return $ONLINEIP;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.