What are the best practices for handling user input and preventing vulnerabilities like directory traversal attacks in PHP?

Directory traversal attacks occur when an attacker manipulates user input to access files outside of the intended directory. To prevent this vulnerability in PHP, it is important to sanitize and validate user input before using it to access files on the server. One way to do this is by using the realpath() function to resolve the full path of a file and compare it with a base directory to ensure it is within the allowed directory.

$baseDir = '/path/to/allowed/directory/';

$userInput = $_GET['file'];

$filePath = realpath($baseDir . $userInput);

if (strpos($filePath, $baseDir) !== 0) {
    die('Invalid file path');
}

// Proceed with accessing the file using $filePath