What are the potential security risks of using a simple if statement to restrict downloads based on file size in PHP?

Using a simple if statement to restrict downloads based on file size in PHP can be risky as it may not account for all potential security vulnerabilities such as file type manipulation or injection attacks. To mitigate these risks, it is recommended to validate the file type and size before allowing the download to ensure that only safe and appropriate files are being accessed.

// Validate file type and size before allowing download
$file = $_GET['file'];

// Check if file exists and is within acceptable size limit
if (file_exists($file) && filesize($file) < 1048576) {
    // Proceed with download
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($file) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    readfile($file);
    exit;
} else {
    // Invalid file or size exceeds limit
    echo "Invalid file or file size exceeds limit.";
}