Every client that sends a request to your website on the internet has a logical address known as the client’s
If you have access to a client’s IP address, you can perform any of the following actions:
Superglobals are inbuilt variables in PHP, predefined and accessible throughout the entire script. As they concern accessibility, they are not scope bound.
Some examples of Superglobals include:
$_POST
$_GET
$_SESSION
$_REQUEST
$_SERVER
The $_SERVER
superglobal provides header, path, and script location information. It can also accepts several other properties.
To get a user’s IP address, you can use the superglobal $_SERVER
and one of its properties called REMOTE_ADDR
.
The syntax to obtain the REMOTE_ADDR
property is shown below.
$_SERVER[REMOTE_ADDR]
You can use the syntax above to return the IP address of a user on your site, as shown below.
<?PHP
$message ="Your latest visitor is: ";
echo $message, $_SERVER[REMOTE_ADDR];
?>
In the code above, the visitor’s IP address will be displayed on the screen.
When a visitor goes through a
The code below shows how you can get the IP address of visitors behind a proxy.
<?phpfunction visitorIP() {//Check if visitor is from shared networkif(!empty($_SERVER['HTTP_CLIENT_IP'])) {$vIP = $_SERVER['HTTP_CLIENT_IP'];}//Check if visitor is using a proxyelseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){$vIP = $_SERVER['HTTP_X_FORWARDED_FOR'];}//check for the remote address of visitor.else{$vIP = $_SERVER['REMOTE_ADDR'];}return $vIP;}$vIP = visitorIP();echo 'The visitors Real address : '.$vIP;?>?>
PHP allows you to do a hostname to IP address translation for any gethostbyname()
function. However, you need to ensure that you are on the same network as the site’s server.
<?php$ip_address = gethostbyname("www.wikipedia.com");echo "IP Address of Wikipedia is - ".$ip_address;echo "</br>";$ip_address = gethostbyname("www.educative.io");echo "IP Address of Educative is - ".$ip_address;?>
The code above will return the IP addresses of the web address indicated.