Sunday, April 29, 2012

Using Require to Boost Per-File Access Security in PHP

Require is a really neat function, compared to include.  You can use it for security purposes.  For example, consider that you have a database that's based on simple text-files.  Theoretically, someone could type in the URL of those text-files (like "domain.com/text-document.txt"), and view them directly in their browser.  This is as opposed to what you want: those files only to be viewable through your own PHP script.  Otherwise, the data won't be properly formatted, or much worse, you won't be able to do a proper secure authorization or authentication.  So, here's the trick.  Rename your .txt files to .php files.  The first line should be this...

<?php

    require('this_file_does_not_exist_and_will_never_exist');

?>

Then, after that first line, the rest of the file is your database information.  If someone tries access the file directly, they'll get an error, and see no information (danged hackers!).  But, your PHP script that displays the database file will know that this line is there.  This is assuming that you reprogram your text-database, php-front-end to ignore the first line of files when reading data.  For instance, you'll read in the .php data file using the file() function, which gives you an array of with each element representing one line, and then just ignore element 0, because you know it's going to be the PHP code: "require('this_file_does_not_exist_and_will_never_exist');".

It's not encryption, but it's powerful security, quick and cheap, for custom-built databases.

Note:  The most immediate way someone would attempt to hack past this is in attempting to view the original source of the PHP file, which itself is a setting set up in the Linux Apache Server.  So, why not use security through that method?  Easy.  Make a ".htaccess" file for the folder you want to protect, and include this one single line in it, "deny from all".  That will stop access from anyone getting into the folder where that ".htaccess" file is located and any of the folders within that folder.

Official Function Page: http://www.php.net/manual/en/function.require.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment