php 实现视频下载
使用 PHP 实现视频下载的方法
通过文件流直接输出视频内容
使用 readfile() 函数读取视频文件并直接输出到浏览器,设置合适的 HTTP 头部强制下载:
$file_path = '/path/to/video.mp4';
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file_path).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
readfile($file_path);
exit;
分段下载大视频文件
对于大文件,使用 fread() 分段读取避免内存溢出:
$file_path = '/path/to/large_video.mp4';
$chunk_size = 1024 * 1024; // 1MB per chunk
$handle = fopen($file_path, 'rb');
header('Content-Type: video/mp4');
header('Content-Length: ' . filesize($file_path));
header('Content-Disposition: attachment; filename="video.mp4"');
while (!feof($handle)) {
echo fread($handle, $chunk_size);
ob_flush();
flush();
}
fclose($handle);
从远程 URL 下载视频
使用 file_get_contents() 或 CURL 获取远程视频后保存到本地:
$remote_url = 'https://example.com/video.mp4';
$local_path = 'downloaded_video.mp4';
$video_data = file_get_contents($remote_url);
file_put_contents($local_path, $video_data);
使用 CURL 处理重定向和认证
对于需要处理 HTTP 认证或重定向的远程视频:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com/video.mp4');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$video_data = curl_exec($ch);
file_put_contents('video.mp4', $video_data);
curl_close($ch);
注意事项
- 确保服务器有足够的存储空间和内存处理大文件
- 检查文件权限是否允许读写操作
- 对于公开下载链接需验证用户权限
- 考虑添加下载限速防止服务器过载
以上方法可根据实际需求组合使用,例如先通过 CURL 获取远程视频再分段输出给用户下载。







