I am interested to know what is considered more secure out of
include $_SERVER['DOCUMENT_ROOT'] . '/config/special.php';
and
include '../config/special.php';
I see a lot of answers on Stack Overflow and elsewhere on the web that say to store data outside the document root. I have also seen a lot of tutorials that say to include a file in php do something like
include $_SERVER['DOCUMENT_ROOT'] . '/config/special.php';
Would it be ok to do the above if you change the permissions on the folder to something like drwxr-x-wx so you get forbidden if you are trying to access the path in the url (or is this still considered a risk) or would it be better to move my config above my root folder like the below.
include '../config/special.php';
The answer is: “how secure is the rest of your server”?
If you forbid access to the directory from Apache remote calls, you’ve solved half of the issue regardless of where you store your files. However, this isn’t the silver bullet of security. If it was, people would know about it! (I proved this where I work a month ago – one of the lead devs thought that storing stuff in a non-webroot subfolder would make everything secure. Little did he know about the file explorer that he built, and more importantly, how it could take
../as a parameter and work accordingly… 30s later, database got dumped – on a dev environment).The key to security is to harden everything. If you allow users to read files, make sure to ban the
..and...operators, and anything related to it, to prevent them from traversing up the directory chain. Prevent outside users from reading the file (.htaccesswith Apache), and that should deter most people.Depending on how you sanitize the up-one and up-two chains, however, you might end up with more issues. Take the example of my co-worker again: after the dump, he decided to operate these replacements:
(Order is important)
Little did he know about me putting in …. . First regexp would turn this into .., second regexp would do nothing. Bingo, database got dumped. Again.