php实现自动下载
实现自动下载功能
在PHP中实现自动下载功能可以通过设置HTTP头信息和读取文件内容来完成。以下是几种常见的方法:
使用header()函数强制下载
通过设置Content-Type、Content-Disposition等HTTP头信息,可以强制浏览器下载文件而不是在浏览器中打开。
$file = 'path/to/your/file.pdf';
if (file_exists($file)) {
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;
}
自动下载远程文件
需要从远程URL下载文件并保存到服务器,可以使用file_get_contents()或cURL。
$url = 'http://example.com/file.zip';
$savePath = 'local/path/file.zip';
$fileContent = file_get_contents($url);
if ($fileContent !== false) {
file_put_contents($savePath, $fileContent);
}
使用cURL下载文件
cURL提供了更多的控制选项,适合需要更复杂处理的下载任务。
$url = 'http://example.com/file.zip';
$savePath = 'local/path/file.zip';
$ch = curl_init($url);
$fp = fopen($savePath, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
定时自动下载
结合crontab可以实现定时自动下载。创建一个PHP脚本并设置cron任务。
// download_script.php
$url = 'http://example.com/daily/data.csv';
$savePath = '/var/www/data/daily_'.date('Y-m-d').'.csv';
file_put_contents($savePath, file_get_contents($url));
然后在crontab中添加任务:
0 3 * * * /usr/bin/php /path/to/download_script.php
处理大文件下载
对于大文件下载,使用readfile()函数可以避免内存问题。
$file = 'large_file.iso';
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
// 清除输出缓冲
while (ob_get_level()) {
ob_end_clean();
}
readfile($file);
exit;
}
注意事项

- 确保服务器有足够的权限读写文件
- 处理下载前验证文件存在性
- 对于敏感文件,应该添加身份验证
- 大文件下载时考虑使用分块传输或断点续传
- 注意设置正确的MIME类型
这些方法可以根据具体需求组合使用,实现各种自动下载场景。






