What are some potential security risks associated with automatically downloading files from a server to a local machine using PHP?
One potential security risk associated with automatically downloading files from a server to a local machine using PHP is the possibility of downloading malicious files that could harm the local system. To mitigate this risk, it is important to validate the file being downloaded and ensure it is safe before allowing the download to proceed.
// Validate the file before downloading
$filename = 'example.txt';
$filepath = '/path/to/files/' . $filename;
if (file_exists($filepath)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filepath));
readfile($filepath);
exit;
} else {
echo 'File not found.';
}