How to get the visitor IP in the PHP
You can get the visitor’s IP using REMOTE_ADDR
.
1 |
$visitorIp=$_SERVER['REMOTE_ADDR']; |
If visitors use the proxy server then you will get the IP address of the proxy server. In this case, you need to check the 3 possibilities:
1 2 3 |
$_SERVER['REMOTE_ADDR']; $_SERVER['HTTP_X_FORWARDED_FOR']; $_SERVER['HTTP_CLIENT_IP']; |
$_SERVER[‘REMOTE_ADDR’] is used to find the real IP address of the user.
$_SERVER[‘HTTP_CLIENT_IP’] is used to find the IP address when the user is accessing the page from the shared internet.
$_SERVER[‘HTTP_X_FORWARDED_FOR’] is used to find the IP address when the user uses a proxy to access the webpage.
1 2 3 4 5 6 7 8 9 |
<?php $visitorip = $_SERVER["REMOTE_ADDR"]; if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) { $visitorip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')'; } if (!empty($_SERVER["HTTP_CLIENT_IP"])) { $visitorip .= '('.$_SERVER["HTTP_CLIENT_IP"].')'; } echo $visitorip; |