php实现图片下载
使用 file_get_contents 和 file_put_contents 下载图片
通过 file_get_contents 读取远程图片内容,再用 file_put_contents 保存到本地。适合简单场景,但缺乏错误处理和性能优化。
$imageUrl = 'https://example.com/image.jpg';
$savePath = 'downloaded_image.jpg';
$imageData = file_get_contents($imageUrl);
if ($imageData !== false) {
file_put_contents($savePath, $imageData);
}
使用 cURL 下载图片
cURL 提供更强大的功能,支持设置超时、处理重定向和获取响应头信息。适用于需要精细控制的场景。
$ch = curl_init('https://example.com/image.jpg');
$fp = fopen('downloaded_image.jpg', 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
curl_close($ch);
fclose($fp);
处理大文件下载
对于大文件,采用流式处理避免内存耗尽。结合 fopen 和流上下文实现分块读写。

$src = fopen('https://example.com/large_image.jpg', 'r');
$dest = fopen('large_image.jpg', 'w');
stream_copy_to_stream($src, $dest);
fclose($src);
fclose($dest);
验证图片有效性
下载后检查文件是否为有效图片,避免保存损坏或非图片内容。使用 getimagesize 进行验证。
if (@getimagesize('downloaded_image.jpg') !== false) {
// 图片有效
}
设置用户代理和超时
模拟浏览器请求并防止长时间阻塞,尤其针对需要鉴权的资源。

$context = stream_context_create([
'http' => [
'user_agent' => 'Mozilla/5.0',
'timeout' => 30
]
]);
$imageData = file_get_contents($imageUrl, false, $context);
处理 HTTPS 证书问题
在开发环境中忽略 SSL 证书验证,但生产环境应配置有效证书。
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
生成唯一文件名
避免文件名冲突,使用时间戳或哈希值生成唯一标识。
$extension = pathinfo($imageUrl, PATHINFO_EXTENSION);
$savePath = 'images/' . uniqid() . '.' . $extension;






