📞 09318539889 📧 yxp@gansuwangzhan.cn

下载远程图片到指定目录

作者:杨锦龙时间:2026-05-28点击量:0次
/**
 * 下载远程图片到指定目录
 * @param string $url     远程图片URL
 * @param string $saveDir 保存目录(相对于根目录或绝对路径均可)
 * @return array
 */
public function download($url,$saveDir)
{
    try {
        // 1. 确保目录存在(TP5.1 中建议使用绝对路径或 ROOT_PATH 拼接)
        if (!is_dir($saveDir)) {
            mkdir($saveDir, 0755, true);
        }

        // 2. 使用 cURL 获取图片内容
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (compatible; TP5.1-Downloader)',
        ]);
        $imageData = curl_exec($ch);
        $httpCode  = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        if ($imageData === false || $httpCode !== 200) {
            return ['success' => false, 'message' => "下载失败(HTTP:{$httpCode}): {$curlError}", 'path' => ''];
        }

        // 3. 【核心修改】使用 getimagesizefromstring 替代 finfo 验证图片
        $imageInfo = @getimagesizefromstring($imageData);
        if ($imageInfo === false) {
            return ['success' => false, 'message' => '无效的图片文件', 'path' => ''];
        }

        // 4. 生成安全文件名(基于图片真实类型)
        $extMap   = [IMAGETYPE_JPEG => 'jpg', IMAGETYPE_PNG => 'png', IMAGETYPE_GIF => 'gif', IMAGETYPE_WEBP => 'webp'];
        $ext      = $extMap[$imageInfo[2]] ?? 'jpg';
        $fileName = md5($imageData) . '.' . $ext; // 用内容哈希命名,避免重复和特殊字符
        $savePath = rtrim($saveDir, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $fileName;

        // 5. 写入文件
        if (file_put_contents($savePath, $imageData) === false) {
            return ['success' => false, 'message' => '文件写入失败', 'path' => ''];
        }
        $savePath1 = str_replace(ROOT_PATH,"",$savePath);
        $normalizedPath = str_replace('\\', '/', $savePath1);
        return ['success' => true, 'message' => '下载成功', 'path' => $normalizedPath,'filename'=>$fileName];

    } catch (\Throwable $e) {
        return ['success' => false, 'message' => $e->getMessage(), 'path' => ''];
    }
}