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

PHP开发需求:追踪URL全跳转链路并输出除原链接外的跳转链接

捕获所有HTTP跳转链路的PHP实现

你的现有代码只能获取最终跳转后的URL,无法捕获中间的跳转链路,原因是开启了CURLOPT_FOLLOWLOCATION让curl自动跟随跳转,跳过了中间步骤。要实现全链路捕获,需要禁用自动跳转,手动解析每个响应的Location头并循环请求。

以下是完整的实现代码:

<?php
$originalUrl = "https://stvkr.com/v2/click-bOv2R-8X5JXO-14EJa-b6974c6b?tl=1";
$currentUrl = $originalUrl;
$redirectChain = [];

// 初始化curl会话
$ch = curl_init();
// 核心设置:禁用自动跟随跳转,手动处理每个跳转
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
// 要求返回响应头
curl_setopt($ch, CURLOPT_HEADER, true);
// 将响应内容返回给变量,而非直接输出
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 可选:处理HTTPS证书验证(生产环境建议启用并配置CA证书)
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

// 循环处理跳转,直到没有Location头
do {
    curl_setopt($ch, CURLOPT_URL, $currentUrl);
    $response = curl_exec($ch);
    
    // 获取响应头的长度,分离头和响应体
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $headers = substr($response, 0, $headerSize);
    
    // 解析响应头中的Location字段
    $nextLocation = null;
    foreach (explode("\r\n", $headers) as $headerLine) {
        if (stripos($headerLine, 'Location:') === 0) {
            $nextLocation = trim(substr($headerLine, 9));
            // 处理相对路径跳转(比如Location: /path)
            if (strpos($nextLocation, 'http') !== 0) {
                $parsedCurrent = parse_url($currentUrl);
                $baseUrl = $parsedCurrent['scheme'] . '://' . $parsedCurrent['host'];
                // 拼接相对路径
                $nextLocation = rtrim($baseUrl, '/') . '/' . ltrim($nextLocation, '/');
            }
            break;
        }
    }
    
    // 如果存在有效跳转链接,加入链路数组
    if ($nextLocation && $nextLocation !== $currentUrl) {
        $redirectChain[] = $nextLocation;
        $currentUrl = $nextLocation;
    } else {
        $nextLocation = null;
    }

} while ($nextLocation);

// 关闭curl会话
curl_close($ch);

// 输出除原始链接外的所有跳转链路
echo "跳转链路列表:\n";
foreach ($redirectChain as $idx => $url) {
    echo ($idx + 1) . ". " . $url . "\n";
}
?>

关键说明

  1. 禁用自动跳转:通过CURLOPT_FOLLOWLOCATION = false,让curl停留在每个跳转步骤,返回完整的响应头供解析。
  2. 解析Location头:从响应头中提取跳转目标URL,同时处理相对路径的情况,确保生成完整的绝对URL。
  3. 循环终止条件:当响应头中没有Location字段,或者跳转目标与当前URL相同时,停止循环。
  4. 链路收集:所有中间跳转URL都会被存入$redirectChain数组,最终输出的就是除原始链接外的所有跳转路径。

注意事项

  • 跳转次数限制:可以添加计数器(比如$maxRedirects = 10),防止因循环跳转导致的死循环。
  • SSL证书验证:生产环境中建议移除CURLOPT_SSL_VERIFYPEER和CURLOPT_SSL_VERIFYHOST的禁用设置,配置正确的CA证书路径。
  • 编码处理:如果跳转URL包含特殊字符,可使用rawurlencode()对路径部分进行编码,避免解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:21:56