How to obtain the Client IP address in PHP

Source: Internet
Author: User
Tags php website
The getenv ('remote _ ADDR ') method mentioned in PHP manual has many problems in obtaining the Client IP address, therefore, it is necessary to consider using a more comprehensive method to obtain the IP address of the user client more accurately. Getenv

(PHP 3, PHP 4, PHP 5)

Getenv -- gets the value of an environment variable

Description

StringGetenv(String varname)

Returns the value of the environment variableVarname, OrFalseOn an error.

<?php// Example use of getenv()$ip=
getenv('REMOTE_ADDR');// Or simply use
a Superglobal ($_SERVER or $_ENV)$ip =
$_SERVER['REMOTE_ADDR'];?>

This is the method provided by manual, the official PHP website.

However, when the Web Server API isAsapi (IIS)The getenv function does not work. In this case, if you use getenv to obtain the IP address of the client, the IP address is incorrect.

Therefore, the safer and more accurate method is to avoid using the getenv function. For example, you can use the following function to obtain IP information:

// Get the real client IP ("bullet-proof ")

Function getip (){
If (getenv ("http_client_ip ")&&
Strcasecmp (getenv ("http_client_ip"), "unknown "))
$ IP =
Getenv ("http_client_ip ");
Elseif (getenv ("http_x_forwarded_for ")&&
Strcasecmp (getenv ("http_x_forwarded_for"), "unknown "))
$ IP =
Getenv ("http_x_forwarded_for ");
Elseif (getenv ("remote_addr ")&&
Strcasecmp (getenv ("remote_addr"), "unknown "))
$ IP =
Getenv ("remote_addr ");
Elseif (isset ($ _ server ['remote _ ADDR ']) &
$ _ Server ['remote _ ADDR '] &
Strcasecmp ($ _ server ['remote _ ADDR '], "unknown "))
$ IP =
$ _ Server ['remote _ ADDR '];
Else
$ IP =
"Unknown ";
Return ($ IP );
}

For more detailed discussion, see http://cn.php.net/manual/zh/function.getenv.php

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.