Sometimes, you might want to get user IP address using PHP in your PHP application for authorization or logging purposes. This article will show you how to do so.
The quickest way to get user IP address using PHP is by getting the
$userIP = $_SERVER['REMOTE_ADDR'];
This will return the current user IP address (your IP, when viewing the page yourself).
However, getting user IP address using this variable isn’t always reliable. Except the case that user spoofing their IP address (by using VPN for example), the IP address might not be accurate if your server is behind a WAF (Web Application Firewall, such as CloudFlare).
The below section will further guide you on multiple cases to get the accurate user IP address in PHP.
Tutorial StartsTo get user IP address using PHP
Get the right IP variable
As the intro, the basic
$_SERVER variable for getting user IP address is
However, if your server is behind a WAF (Web Application Firewall), the variable will be different. There are different type of WAF, but we will point out the commonly used WAF, CloudFlare and Imperva (Incapsula).
- For CloudFlare, the correct variable of user IP address is
- For Imperva (Incapsula), the variable is
After figuring out the correct IP variable, we can get user IP address using multiple methods.
Get user IP address methods
First, create a PHP file with the following line:
Save the file, open it on the browser, and lookup the IP variable mentioned in the previous section.
Example for the web server using Imperva Web Application Firewall:
To view user IP address by echoing the
$_SERVER variable, simply echo the proper IP variable mentioned in the above section to view user IP address:
<?php // Native IP address echo $_SERVER['REMOTE_ADDR']; // CloudFlare echo $_SERVER['HTTP_CF_CONNECTING_IP']; // Imperva (Incapsula) echo $_SERVER['HTTP_INCAP_CLIENT_IP'];
With the correct
$_SERVER variable, it is easy to get user IP address using PHP. While it’s not always 100% correct, especially when the user intended to spoof their IP address, it’s accurate enough for general use cases.