php 实现视频下载
使用 PHP 实现视频下载
方法一:通过 file_get_contents 和 file_put_contents 下载
$videoUrl = 'https://example.com/video.mp4';
$savePath = 'downloaded_video.mp4';
$videoData = file_get_contents($videoUrl);
file_put_contents($savePath, $videoData);
确保服务器配置允许使用 file_get_contents 函数访问外部 URL。如果需要处理大文件,这种方法可能不适合,因为它会一次性将整个文件加载到内存中。
方法二:使用 cURL 下载大文件
$videoUrl = 'https://example.com/video.mp4';
$savePath = 'downloaded_video.mp4';
$ch = curl_init($videoUrl);
$fp = fopen($savePath, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
cURL 方法更适合下载大文件,因为它支持流式传输,不会一次性占用大量内存。

方法三:处理分块下载和断点续传
$videoUrl = 'https://example.com/video.mp4';
$savePath = 'downloaded_video.mp4';
$ch = curl_init($videoUrl);
$fp = fopen($savePath, 'a'); // 使用追加模式
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RESUME_FROM, filesize($savePath)); // 断点续传
curl_exec($ch);
curl_close($ch);
fclose($fp);
这种方法可以处理中断的下载,通过检查已下载文件大小并从中断处继续下载。

方法四:添加用户代理和超时设置
$videoUrl = 'https://example.com/video.mp4';
$savePath = 'downloaded_video.mp4';
$ch = curl_init($videoUrl);
$fp = fopen($savePath, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
curl_setopt($ch, CURLOPT_TIMEOUT, 120);
curl_exec($ch);
curl_close($ch);
fclose($fp);
设置用户代理和超时时间可以避免被目标服务器拒绝,并防止长时间无响应的连接。
方法五:通过 PHP 下载并强制浏览器保存
$videoUrl = 'https://example.com/video.mp4';
$filename = 'video.mp4';
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($videoUrl));
readfile($videoUrl);
exit;
这种方法直接将视频文件发送给浏览器,触发下载对话框。注意确保 $videoUrl 是服务器上的本地路径或可访问的远程文件。
注意事项
- 确保有权限下载目标视频文件,避免侵犯版权。
- 处理大文件时考虑服务器内存限制和执行时间限制。
- 对于远程文件下载,检查目标服务器是否允许热链接。
- 考虑使用队列系统处理大批量下载任务,避免阻塞主线程。
- 实现适当的错误处理机制,捕获并记录下载过程中的异常。






