What potential security risks are associated with directly accessing the file system using user input in PHP?

Directly accessing the file system using user input in PHP can lead to security risks such as directory traversal attacks, where an attacker can navigate through the file system to access sensitive files. To mitigate this risk, it is important to validate and sanitize user input before using it to access the file system.

// Sanitize user input before accessing the file system
$user_input = filter_var($_GET['file_path'], FILTER_SANITIZE_STRING);

// Check if the file path is within a specific directory
$allowed_directory = '/path/to/allowed/directory/';
$real_path = realpath($allowed_directory . $user_input);

if (strpos($real_path, $allowed_directory) === 0) {
    // Access the file using the sanitized file path
    $file_contents = file_get_contents($real_path);
    echo $file_contents;
} else {
    echo "Invalid file path.";
}