How do I limit my PHP script to only run when requested by localhost?
An answer to this question on Stack Overflow.
Question
I'm having trouble getting my php page to only run when it is requested by the server itself.
This is what I have right now:
if ($_SERVER['SERVER_ADDR'] == $_SERVER['REMOTE_ADDR']) {
//process page
} else {
$this->redirect('http://' . $_SERVER['HTTP_HOST'] . '/404');
}
However, when I curl it, it doesn't give any errors or return anything at all. If I remove the check, it spits out the HTML as expected.
I tried echoing both of those values and got 192.168.1.186, and 192.168.1.225 respectively. I do realize they are different (this is being run by the server itself), but how can I fix it? This code was from this S.O answer
Answer
The title of your question implies that I can provide an answer which doesn't quite match the body of your question.
My response to this is that putting your entire script in a giant if statement seems somehow insecure and unmaintainable.
You would need a guard like this if it were possible for other computers to run your script, say by accessing it from the web.
But, if the server is the only machine which can run the script, why not just put it in a place where only the server can access it? For instance, one directory level above the web-accessible directory or in a child-directory with 700 permissions. Or use .htaccess to limit access.
That seems both safer and more maintainable.