You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP获取CGI-Bin接口跳转后图片URL遇403错误问题

解决PHP cURL/Laravel Http请求CGI-Bin链接返回403的问题

403 Forbidden通常是服务器拒绝了非浏览器的请求——它检测到请求不是来自真实用户环境。以下是几个可行的解决方案:

1. 补全浏览器风格的请求头

仅设置User-Agent可能不够,服务器往往会检查更多请求头字段来验证请求合法性。把浏览器常用的字段补上,模拟完整的用户请求:

cURL版本优化代码:

$url = 'https://www.adoptapet.com/cgi-bin/public/petsearch.cgi/photo_url?pet_id=29846404&clan_id=1';
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 自动跟随重定向(浏览器默认行为)
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    'Referer: https://www.adoptapet.com/', // 模拟从网站主页跳转过来
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language: en-US,en;q=0.5'
));

$response = curl_exec($ch);
curl_close($ch);

dd($response);

Laravel Http版本优化代码:

$url = 'https://www.adoptapet.com/cgi-bin/public/petsearch.cgi/photo_url?pet_id=29846404&clan_id=1';
$response = Http::withHeaders([
    'User-Agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    'Referer' => 'https://www.adoptapet.com/',
    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language' => 'en-US,en;q=0.5'
])->followRedirects()->get($url);

dd($response);

2. 处理Cookie验证

部分网站会通过会话Cookie确认请求的合法性。你可以先请求目标网站的主页,获取服务器设置的Cookie,再带着这些Cookie请求CGI链接:

cURL示例:

// 先请求主页获取并保存Cookie
$homeUrl = 'https://www.adoptapet.com/';
$ch = curl_init($homeUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt'); // 把Cookie存到本地文件
curl_exec($ch);
curl_close($ch);

// 加载Cookie再请求目标CGI链接
$url = 'https://www.adoptapet.com/cgi-bin/public/petsearch.cgi/photo_url?pet_id=29846404&clan_id=1';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt'); // 读取之前保存的Cookie
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
    'Referer: https://www.adoptapet.com/'
));

$response = curl_exec($ch);
curl_close($ch);

dd($response);

3. 检查URL和参数准确性

注意你提供的两个URL(example.com和adoptapet.com)不一致,务必确保请求的域名、参数名(比如pet_id vs id)和参数值完全与浏览器请求的一致——服务器对参数错误也可能返回403。

4. 避免被识别为爬虫

如果短时间内频繁请求,服务器可能会直接拦截。可以添加随机的请求间隔,或者先模拟浏览几个网站页面,再请求目标CGI链接,让行为更接近真实用户。

内容的提问来源于stack exchange,提问作者Chad Priddle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 01:10:12