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. }

If you have a low-traffic website, consider joining the Money4Banners advertising network. They will pay you £10 + £5 each month for displaying a small advert on three of your pages, regardless of traffic. American webmasters are welcome, and since £10 == $20, you make more!


6 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

Leave a Reply

You must log in to post a comment.


Categories