I'm using the "include" function (e.x. "include 'header2.php'" or "include 'class.users.php'") to add the header or session class in my website. I don't really remember where, but I heard that hackers abuse, somehow, this "include" thing, sending the fake included page or something like that. So basically I would like to know what's with that "include" function, how can I protect it, how do they abuse it and if there are better solutions for what I am looking for.
Thanks in advance.
The biggest issue with includes is likely changing filename extension from PHP to something that doesn't get automatically executed by the web server. For example- library.inc, or config.inc. Invoking these files with a web browser will reveal the code instead of executing it - and any passwords or exploitable hints will be shown.
Compare config.php that might have a password in it with config.inc. Pulling up config.inc would in most cases show what the database password was.
There are programmers who use .inc extensions for libraries. The premise is that they won't be in a directory accessible by a web server. However, less security paranoid programmers might dump that file into a convenient web directory.
Otherwise, ensure that you don't include a file that's submitted by a query string somehow. Ex:
include( $_GET['menu_file'] )
<-- this is very wrong.It all depends on how you implement it. If you specifically set the path, then it's secure. The attack could happen if you allow user input to determine the file path without sanitization or checks.
Insecure (Directory Traversal)
Insecure (URL fopen - If enabled)
Insecure
Partially Insecure ( *.php files are vulnerable )
Secure (Though not sure why anyone would do this.)
Secure
Include is safe provided you don't:
www.someoneelsesssite.com/something.php
www.mysite.com/bad.php?path=oops/here/is/your/passwords/file
2 and 3 technically have the caveat that if you disallow
.
or/
or on windows\
you are probably fine. But if you don't know why, you don't know enough about it to risk it. Even when you think the database is read only or otherwise secure, it is wise to not assume that unless you really have to, which is almost never.As pp19dd's answer points out. It is also vital that you name your includes with the .php extension. If you've set apache (or whatever web server you are using) to parse another file type as PHP too, that's safe as well. But if you don't know for sure, use .php exclusively.
The best thing to do is ensure that the page you are trying to include exists first. The real security loopholes come when your include page is processed from some sort of user input, such as a URL variable.
?include=page.php
As long as you are cautious of these you should be fine.Anything server side (assuming your server isn't compromised) is safe. Doing this:
is insecure.
is secure.
I'm using this method.