php实现素材下载
实现素材下载的PHP代码示例
使用PHP实现文件下载功能,可以通过设置HTTP头部信息并读取文件内容来实现。以下是几种常见的方法:
方法1:直接输出文件内容

$file_path = 'path/to/your/file.jpg';
$file_name = basename($file_path);
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
方法2:使用文件流下载
$file_path = 'path/to/your/file.zip';
$file_name = basename($file_path);
if (file_exists($file_path)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
header('Content-Length: ' . filesize($file_path));
flush();
$file = fopen($file_path, "rb");
while (!feof($file)) {
print fread($file, 1024*8);
flush();
}
fclose($file);
exit;
} else {
http_response_code(404);
die('File not found');
}
方法3:处理远程文件下载

$remote_url = 'http://example.com/file.pdf';
$local_name = 'downloaded_file.pdf';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$local_name.'"');
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $remote_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
echo $data;
exit;
安全注意事项
确保在实现下载功能时添加适当的安全措施:
- 验证用户权限
- 限制可下载的文件目录
- 对文件名进行过滤,防止目录遍历攻击
- 对于大文件,考虑使用分块传输
性能优化建议
对于大文件下载,可以使用以下方法优化:
$chunk_size = 1024 * 1024; // 1MB chunks
$handle = fopen($file_path, 'rb');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
以上代码示例提供了不同场景下的文件下载实现方法,可以根据具体需求选择适合的方案。






