What are the potential pitfalls when trying to access and transfer a file using its name in PHP?

One potential pitfall when trying to access and transfer a file using its name in PHP is not properly sanitizing the input. This can lead to security vulnerabilities such as directory traversal attacks. To solve this issue, always validate and sanitize user input before using it to access or transfer files.

// Sanitize the file name before using it
$fileName = filter_var($_GET['file'], FILTER_SANITIZE_STRING);

// Transfer the file using the sanitized file name
$file = '/path/to/files/' . $fileName;
if (file_exists($file)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    readfile($file);
    exit;
} else {
    echo 'File not found';
}