Reputation: 43
There are a lot of ways for detecting if you are running PHP code on localhost or server. However they use $_SERVER and http header which can be fake by user.
It is serious for me because I have made a developer php shell interactive on my website which should go to 404 if it is not on the localhost.
Upvotes: 4
Views: 7992
Reputation: 449485
The most straightforward answer is $_SERVER["REMOTE_ADDR"]
. It's generally considered reasonably safe.
However, if you provide access to command line commands through your script, it may not be enough. It may be possible to send a request to your script from the outside through IP spoofing. That may be enough to trigger a destructive command even though IP spoofing usually means that the attacker will not receive a response. (This is a very esoteric scenario and I know little more about it than that it may be possible.)
What you could do:
Instead of checking the IP from within PHP, make sure the page can not be accessed from the outside using tougher means, for example by setting up a hardware or software firewall that prevents any access from outside, or configuring your web server to listen only to local requests.
Instead of checking the IP from within PHP, protect the page by using some sort of password authentication.
Talk to a security expert (maybe on http://security.stackexchange.com), explain your network setup and ask for opinions whether IP spoofing is a possibility in your specific scenario.
Make your script available through CLI, the server's local command line, instead of the web server. Place your script outside the web server's root. (This option will probably defeat your specific purpose of having an interactive shell, though)
Or you can of course trust that no one will ever find out. If this is for a low-risk, private project, thinking about IP spoofing is probably overthinking it massively.
Upvotes: 2
Reputation: 10975
I believe you are looking for $_SERVER['REMOTE_ADDR']
.
Check it with localhost or 127.0.0.01 or a LAN IP of your choice.
Pekka 웃 with his answer goes into further details on how this may be spoofed.
Upvotes: 1
Reputation: 713
$serverList = array('localhost', '127.0.0.1');
if(!in_array($_SERVER['HTTP_HOST'], $serverList)) {
}
you can't fake this one
Upvotes: -1