What are the best practices for handling user input in PHP to prevent directory traversal attacks?

Directory traversal attacks occur when a user input is not properly sanitized, allowing malicious users to navigate through directories they should not have access to. To prevent this, it is essential to validate and sanitize all user input before using it in file operations. One common method to prevent directory traversal attacks in PHP is to use the realpath() function to resolve any relative paths to their absolute paths before performing any file operations.

$userInput = $_GET['file'];

$filePath = realpath('uploads/' . $userInput);

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

// Proceed with file operations using $filePath