Search code examples
phpxhtmlincluderestriction

Restrictions on PHP include()


I am separating some XHTML from PHP by putting the XHTML into a separate file and then using PHP's include() function within the PHP script.

This works perfectly fine, however, users are still able to access the .html file directly if they know the address. They can't really do much with it, but I would rather it not show.

I've seen some scripts in the past use some form of referrer check, is this what I would do to add some basic (Notice I said 'basic') restrictions to prevent it from being viewed by accessing it directly?

Thanks!

Clarification: I forgot to mention that I want to do this within PHP, so no web-server configuration (Moving files out of document-root, configuring web-server to disallow access, etc.). I think the most logical choice here is to use the define() constant check, that's actually indeed what I've seen in other scripts that I had forgotten, as I outlined in my post. I realize this is probably not the best solution, but given that the html file that can be access is of no particular value, the define() constant should suffice.


Solution

  • If you currently place all your files (like index.php) in /something/public_html/ you will want to move the files to /something/. That way users cannot access the files.

    The /public_html/ is called your document root. That folder is mapped to example.com, and and basically the website starts there. If you move the files to above where the website starts, no one can access those files via a browser.

    As Ignacio said, this will not work with include if safe mode is turned on.

    Other methods are to place something at the top of the file thats says

    if(!defined("RUNNING_SCRIPT"))
        die("No Direct Access Allowed");
    

    and then in your PHP files put

     define("RUNNING_SCRIPT", true);
    

    If RUNNING_SCRIPT is not defined, that means they are directly accessing it, and it stops the page from loading. This only works though if PHP runs on the .html files.

    You could also use a .htaccess file to disallowed access to that folders.