What are the best practices for handling user input in PHP to prevent unauthorized access to files or directories?

When handling user input in PHP, it is important to sanitize and validate the input to prevent unauthorized access to files or directories. One way to do this is by using functions like `filter_input()` to sanitize user input and `realpath()` to ensure that the paths are valid and safe to use.

$user_input = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_STRING);

$base_dir = '/path/to/secure/directory/';
$full_path = realpath($base_dir . $user_input);

if(strpos($full_path, $base_dir) !== 0){
    die('Unauthorized access');
}

// Proceed with accessing the file using $full_path