Find a visitor’s IP address with PHP

Do you want to know the IP address of a visitor? This can be useful for many reasons, such as tracking site usage or blocking access to specific people. Here’s how you can find it using PHP.

In a PHP page, within the PHP tags, <?php ... ?>, you can retrieve the IP address of a user through the server variables array, which is contains information about the user and the server environment and is accessible from anywhere in your PHP script. To do this, you use the code $_SERVER['REMOTE_ADDR']. It works like a normal array, where REMOTE_ADDR is the key, and the IP address of the visitor is the value associated with that key.

Display The IP Address

So, if you want to display the IP Address to the user then the following page will suffice:

  echo "Hello! Your IP Address is: " . $_SERVER['REMOTE_ADDR'];

Exploring the $_SERVER array

You might be wondering what other information you can get from $_SERVER, well you can find out with the following script which displays all the variables in it along with their values if set, in a HTML table:

<table border="1">
    foreach( $_SERVER as $key => $value ) {
      echo "<tr><td>" . $key . "</td>";
      echo "<td>" . $value . "</td></tr>";

Finally, the following code works harder to find the true IP of the user by checking for proxies. This is a function which you can call from elsewhere in your script.

  function userIP()
    //This returns the True IP of the client calling the requested page
    // Checks to see if HTTP_X_FORWARDED_FOR
    // has a value then the client is operating via a proxy
    if($userIP == "")
      $userIP = $_SERVER['REMOTE_ADDR'];
    // return the IP we've figured out:
    return $userIP;