What measures can be taken to restrict user access to specific directories within a PHP script to prevent unauthorized access?
To restrict user access to specific directories within a PHP script and prevent unauthorized access, you can use PHP's built-in functions like `basename()` or `realpath()` to check the requested file paths against a list of allowed directories. Additionally, you can use session variables or user authentication to verify the user's identity before granting access to the directories.
<?php
$allowed_directories = ['/path/to/allowed_directory1', '/path/to/allowed_directory2'];
$user_directory = $_GET['directory'];
if (in_array(realpath($user_directory), $allowed_directories)) {
// User has access to the requested directory
// Proceed with the script logic
} else {
// Unauthorized access
echo "Unauthorized access!";
// You can redirect the user or display an error message
}
?>