php下载文件实现
使用 file_get_contents 和 file_put_contents
适用于小文件下载,直接读取远程文件内容并保存到本地。
$remoteFileUrl = 'https://example.com/file.zip';
$localFilePath = 'local_file.zip';
$fileContent = file_get_contents($remoteFileUrl);
if ($fileContent !== false) {
file_put_contents($localFilePath, $fileContent);
echo "文件下载成功";
} else {
echo "下载失败";
}
使用 cURL 扩展
支持更多自定义选项(如超时、头部信息),适合大文件或需要复杂控制的场景。
$remoteFileUrl = 'https://example.com/file.zip';
$localFilePath = 'local_file.zip';
$ch = curl_init($remoteFileUrl);
$fp = fopen($localFilePath, 'w+');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
$result = curl_exec($ch);
curl_close($ch);
fclose($fp);
if ($result) {
echo "文件下载成功";
}
强制浏览器下载(非保存)
通过设置 HTTP 头部强制浏览器弹出下载对话框。
$filePath = 'path/to/local_file.zip';
$fileName = 'download.zip';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
分块下载大文件
避免内存溢出,逐块读取并输出文件内容。

$filePath = 'large_file.zip';
$chunkSize = 1024 * 1024; // 1MB/块
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment');
$handle = fopen($filePath, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunkSize);
ob_flush();
flush();
}
fclose($handle);
注意事项
- 远程下载需确保
allow_url_fopen开启(file_get_contents)或服务器支持 cURL。 - 检查目标路径可写权限,避免因权限问题失败。
- 大文件下载建议增加超时设置或进度提示。






