To get the current system IP address in php, we can access the ‘REMOTE_ADDR’ key from the $_SERVER super global variable.
$ip_address = $_SERVER['REMOTE_ADDR'];
If the client is using a proxy or accessing your page with shared internet, you use the ‘HTTP_X_FORWARDED_FOR’ and ‘HTTP_CLIENT_IP’ keys respectively.
$ip_address_proxy = $_SERVER['HTTP_X_FORWARDED_FOR'];
$ip_address_shared_internet = $_SERVER['HTTP_CLIENT_IP'];
If you are looking to get the IP address of a particular website, you can do that with the php gethostbyname() function.
$ip_address = gethostbyname("www.google.com");
When designing web pages, many times we need to get the IP address of a visitor for various reasons (logging, targeting, redirecting, etc.)
To get the IP address of a user, we can use the $_SERVER super global variable.
The $_SERVER super global variable has many different values which can be accessed in our program.
To access the IP address of the user, we read the ‘REMOTE_ADDR’ field from $_SERVER.
Below is a simple example of how to retrieve the IP address from a user.
$ip_address = $_SERVER['REMOTE_ADDR'];
How to Get the IP Address of a User Behind a Proxy in php
If the user is using a proxy and accessing your website, then you will need to use a different key to get the IP Address.
To get the IP address of a client using a proxy, you should access the ‘HTTP_X_FORWARDED_FOR’ key in the $_SERVER super global variable.
$ip_address_proxy = $_SERVER['HTTP_X_FORWARDED_FOR'];
If the user is using shared internet, then it’s possible that you will have to check the ‘HTTP_CLIENT_IP’ key in the $_SERVER variable.
$ip_address_shared_internet = $_SERVER['HTTP_CLIENT_IP'];
A full function which will check for all of these cases is below.
function getIPAddress(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip_address = $_SERVER['HTTP_CLIENT_IP'];
} elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip_address = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
How to Get the IP Address of a Website in php
Every website has an IP address. If we need to get the IP address of a particular website, then we can use the php gethostbyname() function.
Pass the URL of the website to gethostbyname() and you will get the IP address of that website.
Below is an example of getting the IP address of www.google.com in php.
$ip_address = gethostbyname("www.google.com");
Hopefully this article has been useful for you to learn how to get IP addresses using php.