Use “Approval Lists” (a.k.a whitelists) in PHP to Restrict Access to Specific Files and Directories

To restrict access to certain files and directories in PHP, you can use either an “approval” list (previously referred to as a “white list”) or an “exclude” (previously black list) approach. The terms have evolved, though the concepts have not. Here are some code samples for both approaches:

  1. Whitelist approach using $_GET or $_POST parameters:
// Define a whitelist of allowed pages
$allowedPages = ['home', 'about', 'contact'];

// Check if the requested page is in the whitelist
if (isset($_GET['page']) && in_array($_GET['page'], $allowedPages)) {
    // Include the requested page
    include($_GET['page'] . '.php');
} else {
    // Display an error message or redirect to a default page
    echo "Invalid page requested!";
}

In this example, a whitelist of allowed pages is defined using an array. The $_GET['page'] parameter is then checked to see if it is in the whitelist. If it is, the corresponding page is included using include(). If not, an error message is displayed or the user is redirected to a default page.

  1. Blacklist approach using .htaccess file:
// Create an .htaccess file in the directory you want to protect 
Deny from all

// Allow access to specific files or directories 
<FilesMatch "^(index\.php|css|js)"> 
    Allow from all 
</FilesMatch>

In this example, an .htaccess file is created in the directory you want to protect. The Deny from all directive prevents access to all files in the directory. The FilesMatch directive is then used to allow access to specific files or directories. In this case, access is allowed to the index.php file, as well as any files in the css and js directories.

By using either a whitelist or blacklist approach to restrict access to certain files and directories, you can help prevent unauthorized access to sensitive files and directories in your PHP application.