Do you want to know the IP address of your website visitors? The following PHP code sample below will show you the IP address of a web page visitor. You may use something as simple as this to start to track your visitors and site members.

The provided PHP code defines a function called getUserIPaddress(), which aims to retrieve the user’s IP address. The function checks different potential sources for the IP address. It first examines if the ‘HTTP_CLIENT_IP’ variable is available, indicating that the IP is directly accessible from the internet. If not, it checks whether the ‘HTTP_X_FORWARDED_FOR’ variable is set, implying that the IP might have been passed through a proxy server. If neither condition is met, the function resorts to using ‘REMOTE_ADDR’, which captures the user’s IP address by default. The function then returns the determined IP address. The code concludes by invoking the getUserIPaddress() function, storing the result in the $userIP variable, and finally, displaying the IP address using the echo statement. This code snippet effectively extracts the user’s IP address, accounting for potential proxies or forwarding mechanisms that could alter the original address.

UPDATED: September 13th, 2023
Consider the following PHP function when checking for a visitors IP address:

This code checks various server variables (HTTP_CLIENT_IP, HTTP_X_FORWARDED_FOR, HTTP_X_FORWARDED, HTTP_FORWARDED_FOR, HTTP_FORWARDED, and REMOTE_ADDR) to determine the visitor’s IP address. It also handles the case where multiple IP addresses might be provided by proxies and takes the first one.

Please note that while this approach is more accurate, it is still subject to potential manipulation by proxies or clients. It’s essential to be aware of these limitations when relying on IP addresses for security or analytics purposes.

 

Find more cool PHP snippets like this in our PHP category.