1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
| use Illuminate\Support\Facades\Http; foreach ($images as $img) { $src = $img->getAttribute('src'); if (str_contains($src, $domain) !== false) continue; try { if (!str_contains($hostname, $strMain)) { $response = Http::withoutVerifying()->head($src); } else { $response = Http::head($src); } if (!$response->ok()) { $statusCode = $response->status(); $errorMessage = "远程图片资源不存在 (状态码: $statusCode)"; if (isset($statusCodeMap[$statusCode])) { $errorMessage .= " - " . $statusCodeMap[$statusCode]; } throw new \Exception($errorMessage); } $parsed = parse_url($src); $path = $parsed['path'] ?? ''; $filename = basename($path); if (empty($filename)) { throw new \Exception('获取图片名错误'); } $imageData = file_get_contents($src); if ($imageData === false) { throw new \Exception('下载失败'); } $isValidImage = true; $finfo = new \finfo(FILEINFO_MIME_TYPE); $detectedMime = $finfo->buffer($imageData); if (!str_starts_with($detectedMime, 'image/')) { $isValidImage = false; } $parsed = parse_url($src); $path = $parsed['path'] ?? ''; $allowedTypes = [ 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif', 'webp' => 'image/webp' ]; if (!in_array($detectedMime, $allowedTypes)) { throw new \Exception("非图片类型"); } $ext = array_search($detectedMime, $allowedTypes); $originalExt = strtolower(pathinfo($path, PATHINFO_EXTENSION)); if ($allowedTypes[$originalExt] == $detectedMime) { $ext = $originalExt; } if (!in_array($originalExt, array_keys($allowedTypes))) { throw new \Exception("非图片类型"); } if (!$isValidImage) { throw new \Exception('文件不是图片'); } $filename = md5(uniqid()) . "." . $ext; $localPath = $fullDir . $filename; file_put_contents($localPath, $imageData); if (isProduction()) { $webPath = "https://" . $domain . $saveDir . $filename; } else { $webPath = "http://" . $domain . $saveDir . $filename; } $img->setAttribute('src', $webPath); $results['success'][] = [ "remote" => $src, "local" => $webPath, ]; $insert[] = [ "url" => $webPath, "remote_url" => $src, "path" => $saveDir . $filename, "admin_id" => auth("plat")->user()->id, "created_at" => $time, "updated_at" => $time, ]; } catch (\Exception $e) { $results['failed'][] = [ "message" => $e->getMessage(), "remote" => $src ]; } }
|