What are the potential security risks of allowing external downloads in PHP?
Allowing external downloads in PHP can pose security risks such as downloading malicious files, exposing sensitive information, and executing harmful scripts on the server. To mitigate these risks, it is important to validate and sanitize the input data, restrict file types, and use secure download methods.
<?php
$allowed_file_types = array('pdf', 'txt', 'jpg', 'png');
$file_url = $_GET['file_url'];
// Validate file URL
if (filter_var($file_url, FILTER_VALIDATE_URL)) {
$file_extension = pathinfo($file_url, PATHINFO_EXTENSION);
// Check if file extension is allowed
if (in_array($file_extension, $allowed_file_types)) {
// Secure download method
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file_url) . '"');
readfile($file_url);
exit;
} else {
echo 'File type not allowed.';
}
} else {
echo 'Invalid file URL.';
}
?>