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:

CODE:
  1. <?php
  2. echo "Hello! Your IP Address is: " . $_SERVER['REMOTE_ADDR'];
  3. ?>

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:

CODE:
  1. <table border="1">
  2. <tr><th>Variable</th><th>Value</th></tr>
  3. <?
  4. foreach( $_SERVER as $key => $value )
  5. {
  6.    echo "<tr><td>" . $key . "</td>";
  7.    echo "<td>" . $value . "</td></tr>";
  8. }
  9. ?>
  10. </table>

Finally, the following code works harder to find the true IP of the user by checking for proxies:

CODE:
  1. function userIP()
  2. {
  3.  //This returns the True IP of the client calling the requested page
  4.  // Checks to see if HTTP_X_FORWARDED_FOR
  5.  // has a value then the client is operating via a proxy
  6.  $userIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
  7.  if($userIP == "")
  8.   {
  9.      $userIP = $_SERVER['REMOTE_ADDR'];
  10.   }
  11.   // return the IP we've figured out:
  12.   return $userIP;
  13. }


7 Responses to “Find a visitor’s IP Address with PHP”  

  1. Gravatar Icon 1 Sarfraz

    I need to save the ip address in some
    table for my own use
    not just to show the visitor

  2. Gravatar Icon 2 Drunken_M

    I need to save the ip adress to…

  3. Gravatar Icon 3 Andrew

    Just use the $userIP and save the value in the table.

  4. Gravatar Icon 4 Ja

    It works only on local network :o ( Whene You are behind proxy or firewall You will get IP of them :o (

  5. Gravatar Icon 5 arun

    Client IP address =$REMOTE_ADDR
    Client Browser = $HTTP_USER_AGENT
    Referral Site = $HTTP_REFERER \n\n\r

  6. Gravatar Icon 6 Synook

    What versions of PHP will this work for…? PHP 4.x or only PHP 5

  7. Gravatar Icon 7 0x666

    Thanks man this is great. Don’t understand how I didn’t find this info searching my ebooks, and so many other websites provide absolute crap. You actually had stuff I could use.

Leave a Reply

You must log in to post a comment.


Categories

Related Entries

  • No related posts.