How to get user IP address using PHP
An IP address helps to identify a device and can show where it's located. It is like an ID or an identity for a device connected to a network. An IP Address helps to track user activities on a website of a particular user and where they are coming from.
In PHP, we can find a device's IP address using either the $_SERVER Global variable or the getenv() function.
Get user IP Address using $_SERVER Global variable
<?php
function getUserIP() {
// Check if the IP is from a shared Internet connection
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
// Check if the IP is from a proxy
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
// Otherwise, get the user's IP address
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
// Get the user's IP address
$userIP = getUserIP();
// Output the user's IP address
echo "User IP Address: " . $userIP;
?>
Above example explanation:
- $_SERVER['HTTP_CLIENT_IP'] This variable returns the IP address of the visitor if they are using a shared Internet connection.
- $_SERVER['HTTP_X_FORWARDED_FOR'] This variable returns the IP address of the user/visiter if they are connecting through a proxy server and their ip forwadrded to another IP.
- $_SERVER['REMOTE_ADDR'] This variable returns the IP address of the user if the above conditions do not match.
Get user IP Address using getenv() function
<?php
echo "IP Address of user" . getenv("REMOTE_ADDR");
?>