PHP: HowTo Read an IP Address of Remote Computer / Browser

How do I read an IP address of remove system or browser using PHP server side programming language? How can I get client IP address and store it to the variable called $ip using php+apache?

PHP has in built facility to detect remote browser, IP address, and other properties. These values are assigned to special variable. In this case, it is assigned to a variable called REMOTE_ADDR. You can use any one of the following statement to obtained or read IP address.

PHP syntax to find out an IP address

The syntax is:

$ip = $_SERVER['REMOTE_ADDR'];

OR

$ip= $REMOTE_ADDR;

OR

$ip = $_SERVER['REMOTE_ADDR'];

OR

$ip = getenv('HTTP_CLIENT_IP');

PHP syntax to find out remote host name

The syntax is:

$ip = $_SERVER['REMOTE_ADDR'];
$hostname = gethostbyaddr($ip);

OR

$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);

Example

Create a file called client-ip.php and store or upload at your Web-server DocumentRoot (e.g. /var/www/html/client-ip.php):

<?php
// client-ip.php : Demo script by SXI LLC <sxi.io>
// get an IP address
$ip = $_SERVER['REMOTE_ADDR'];
// display it back
echo "<h2>Client IP Demo</h2>";
echo "Your IP address : " . $ip;
echo "<br>Your hostname : ". gethostbyaddr($ip) ;
?>

Save and close the file. Open a web-browser and type your url:
http://your-sercer-name-here/client-ip.php
OR
http://127.0.0.1/client-ip.php
Sample outputs:

Fig.01 client-ip.php output

Posted by: SXI ADMIN

The author is the creator of SXI LLC and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.