What are some best practices for validating and filtering user input when using PHP to access and manipulate files?

When working with user input in PHP to access and manipulate files, it is important to validate and filter the input to prevent security vulnerabilities such as directory traversal attacks. One common approach is to use functions like `realpath()` to ensure that the file path is valid and safe to use. Additionally, you can use functions like `basename()` to extract the file name and remove any unwanted characters.

// Example of validating and filtering user input for file manipulation
$user_input = $_POST['file_path'];

// Validate and filter the user input
$clean_file_path = realpath('uploads/' . basename($user_input));

// Use the cleaned file path for file operations
if (file_exists($clean_file_path)) {
    // Perform file operations
    // For example, reading the contents of the file
    $file_contents = file_get_contents($clean_file_path);
    echo $file_contents;
} else {
    echo "File not found.";
}