php实现图片下载
PHP实现图片下载的方法
使用file_get_contents和file_put_contents
通过file_get_contents读取远程图片内容,再用file_put_contents保存到本地。
$url = 'https://example.com/image.jpg';
$savePath = 'downloaded_image.jpg';
$imageData = file_get_contents($url);
file_put_contents($savePath, $imageData);
使用cURL方法
cURL提供更灵活的下载选项,适合需要设置HTTP头或处理重定向的情况。
$url = 'https://example.com/image.jpg';
$savePath = 'downloaded_image.jpg';
$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);
处理大文件下载
对于大文件,建议使用流式处理避免内存问题。
$url = 'https://example.com/large_image.jpg';
$savePath = 'large_image.jpg';
$src = fopen($url, 'rb');
$dest = fopen($savePath, 'wb');
stream_copy_to_stream($src, $dest);
fclose($src);
fclose($dest);
添加HTTP头验证
有些服务器会检查User-Agent等头信息,需要模拟浏览器请求。
$options = [
'http' => [
'method' => 'GET',
'header' => "User-Agent: Mozilla/5.0\r\n"
]
];
$context = stream_context_create($options);
file_put_contents('image.jpg', file_get_contents($url, false, $context));
检查下载是否成功
下载后应验证文件是否存在且内容有效。
if (file_exists($savePath) && filesize($savePath) > 0) {
echo '下载成功';
} else {
unlink($savePath);
echo '下载失败';
}
设置超时限制
防止长时间无响应导致脚本阻塞。
$ctx = stream_context_create([
'http' => ['timeout' => 30]
]);
file_get_contents($url, false, $ctx);
处理文件名
从URL或Content-Disposition头中提取原始文件名。
$pathParts = pathinfo($url);
$extension = $pathParts['extension'] ?? 'jpg';
$savePath = uniqid().'.'.$extension;
批量下载图片
结合循环实现多个图片下载。
$urls = ['url1.jpg', 'url2.png'];
foreach ($urls as $i => $url) {
file_put_contents("image_$i.jpg", file_get_contents($url));
}
注意事项:

- 确保目标目录有写入权限
- 处理可能存在的SSL证书问题
- 遵守目标网站的robots.txt和版权规定
- 添加适当的错误处理机制






