How can I get the real IP address of the client from PHP
if possible.
This means that there is a direct connection, or through a proxy
, or router
or whatever, I always identify the IP
real one of the client computer.
How can I get the real IP address of the client from PHP
if possible.
This means that there is a direct connection, or through a proxy
, or router
or whatever, I always identify the IP
real one of the client computer.
I will share a PHP script that I have created doing research. I use it to know the people who access an Android app that consults data on my server through a URL.
The script shows the following:
Grades:
It's in a script with more options than you're asking for, if you just want to get the IP, you can ignore the other parts like using the Geoplugin, or getting the URL, etc.
Geoplugin is an interesting API a free webmaster resource that easily provides geolocation technology...
It serves to locate the IP and for other things, you can try it online, in the link.
Ok, now we go with the script. I have commented a few things, so that it is very easy to understand:
Code:
Result
Part of the data written to the file:
The codes given in the answers are vulnerable to spoofing and you have to be careful where you use it.
In simple words:
In the answers there are several headers (
HTTP_
) which are not known if they are established by different proxies and the problem is that with the headers theyHTTP
can be easily manipulated:curl --header "X-Forwarded-For: 192.168.0.2" http://example.com
That is, for security ( eg in the authentication environment or similar ), none of these values should be used, since the client/user can modify the header
X_FORWARDED_FOR
orCLIENT_IP
any value, unless you have a trusted reverse proxy .And you should still validate client/user input as it can include dangerous statements in the header
HTTP
, eg:'; DROP TABLE users;--
Not being behind a proxy:
REMOTE_ADDR
will give you a real IP , which will be the most reliable you can get, being the source IP of the TCP connection and cannot be replaced by changing a headerHTTP
.Knowing all this and taking precautions, you can obtain the IP in the following way:
* We use the function
filter_var()
to filter the values with the following indications:FILTER_VALIDATE_IP
FILTER_FLAG_NO_PRIV_RANGE
:FILTER_FLAG_NO_RES_RANGE
:Sources:
Based on your question, try this method. Hope this can help you.