How to Get User IP Address in PHP?

Problem:

May be you plan to display location-wise ads on your website. Certain ads will be visible from a specific location only. For this to happen, you need to know visitor’s IP address. You have other reasons to know visitor’s IP address.

Solution:

Use the environmental variable REMOTE_ADDR to get your website user’s IP address. This provides the most reliable source of information about your visitor’s IP. You can use REMOTE_ADDR in any of the two following ways-

Method 1: Using predefined variable $_SERVER[‘REMOTE_ADDR’]

Web server enters some useful information in the $_SERVER[] array, one of these is visitor’s IP address. To retrieve the visitor’s IP address, use environmental variable REMOTE_ADDR as key in the $_SERVER[] array like $_SERVER[‘REMOTE_ADDR’]. See how to use it in the following example –

<?php
$ip = $_SERVER["REMOTE_ADDR"];
echo "IP address is " . $ip;
?>

[wpdm_file id=42]

Output:
If you run the above code, it will show your IP address

Method 2: Using getenv(“REMOTE_ADDR”) function

getenv() function can display the value of the environmental variables of web server. It takes one environmental variable as parameter and returns its value. To show visitor’s IP address, use REMOTE_ADDR with the function. See how it works in the example below-

<?php
$ip = getenv("REMOTE_ADDR");
echo "IP address is " . $ip;
?>

[wpdm_file id=43]

Output:
If you run the above code, it will show your IP address

Things you should know about the methods

  • The above script may not display your IP address if you run it in your local server. Run it online.
  • If your visitor is using proxy server, you’ll get the IP of that proxy, not the visitor’s real IP address.
  • To see if the environmental variable REMOTE_ADDR is listed in your web server, run the phpinfo() function. It will also display all the other environmental variables.