What are some best practices for filtering directories and files in PHP scripts to enhance security?

When working with directories and files in PHP scripts, it is crucial to filter user input to prevent malicious attacks such as directory traversal or file inclusion vulnerabilities. One best practice is to use functions like realpath() to resolve symbolic links and ensure that the path is valid. Additionally, sanitize user input by using functions like basename() to extract the filename and remove any unwanted characters.

// Example of filtering directories and files in PHP scripts
$directory = '/path/to/directory/';
$file = $_GET['file'];

// Validate and sanitize user input
$file = basename($file);

// Check if the file exists in the specified directory
if (file_exists($directory . $file)) {
    // Process the file
    echo "File found: " . $directory . $file;
} else {
    echo "File not found";
}