There are a few ways to stop direct access of a page. I will go over a few simple techniques that will help out those of you that are just getting into PHP.
Method number 1
Assuming that all of your pages require a function that was made by yourself and is brought in from another page. ie: “require_once(‘functions.php’);” then we can just do a simple check for the function.
1 2 3 4 5 6 | <?php if(!function_exists('yourfunction'){ header('/index.php'); die('Page cannot be accessed directly.'); } ?> |
Method 2
This way of checking for the page is usually a good idea for pages that handle process information. Whether that information is handled through get or post you will still be able to use this form factor.
1 2 3 4 5 6 | <?php if(!isset($_GET['id']){ header('location: index.php'); die('You cannot access this page directly.'); } ?> |
Just a little note for using GET and POST information. PHP is a lot more strict then people will give it credit for and this is because most of the time the errors are small and turned off. If you were to take a look at your error log you will get an entry whenever a page loads a variable with GET or POST and said GET or POST does not exist. For this reason you should check if it is set prior to loading the content into any variable.
Summary of Methods
In this short tutorial we have gone over how to prevent page access. Although these are good clean ways to prevent users from seeing pages that you don’t want them to see it is often easier to modify your HTACCESS page to prevent a page from being access directly a quick way would be do add this your .htaccess file.
1 2 3 4 | <files process.class.php> order allow,deny deny from all </files> |