If you are not using services such as Cloudflare, Incapsula and neither Sucuri, among others, you can use:
$_SERVER['REMOTE_ADDR'];
This will return the IP of the user, if he is using proxy will return the IP of the proxy he is using, however it is better than trusting the X-FORWARDED-FOR
.
If you’re using Cloudflare:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
If you’re using Incapsula:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_INCAP_CLIENT_IP'];
If you are using the Sucuri:
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_SUCURI_CLIENTIP'];
Remember that it is extremely necessary to recur direct connections to the server, restricting access to the site to connections originating from these services. Otherwise, it will allow a Spoofing IP. This is because any header can be changed or inserted by the client, in which case it could include a HTTP_CF_CONNECTING_IP
arbitrary and send out the request from Cloudflare.
In this case, from Cloudflare, only authorize access to Ips from Cloudflare, this will prevent someone from connecting directly to your server and specify a HTTP_CF_CONNECTING_IP
arbitrary, you can see an example of this setting in specific here.
that’s right vlw gave right Aki.
– Wendel Gomes
This function is very dangerous. The
HTTP_CLIENT_IP
and theHTTP_X_FORWARDED_FOR
are headers sent by the user, which can be changed and manipulated. Including, theX_FORWARDED_FOR
may have one more IP separated by comma. Someone commented on this in the original English post as well, not in those words, but here’s the warning.– Inkeliz
@Inkeliz Correct, I saw this warning, so I recommended that you take a good look at the topic, since this would be the simplest solution in PHP, but it has its caveats
– Leonardo Rodrigues