PHP/cURL如何等待重定向并获取最终跳转URL
PHP获取重定向最终URL解决方案
你当前拿到的Location: redirecting...对应的是过渡页面,该页面未返回服务端3xx重定向,而是通过前端meta标签或JavaScript代码实现二次跳转,curl默认的跟随重定向仅识别服务端3xx响应的Location头,无法处理前端跳转逻辑,因此需要分场景处理:
场景1:仅存在服务端3xx多重重定向
直接开启curl内置的跟随重定向功能,通过curl内置参数即可直接获取最终URL,无需自行解析响应头:
$url = 'http://168.0.51.253:8000/boleto/74140-P2UTT5T4IH/'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 开启跟随重定向 curl_setopt($ch, CURLOPT_MAXREDIRS, 10); // 限制最大重定向次数,避免死循环 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 若目标HTTPS证书异常可添加,生产环境建议开启验证 curl_exec($ch); // 直接获取最终跳转URL $finalUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); curl_close($ch); var_dump($finalUrl);
场景2:存在前端(meta/JS)跳转(即你当前遇到的情况)
需要逐次解析每一层响应的内容,提取跳转地址直到没有新的跳转为止:
$url = 'http://168.0.51.253:8000/boleto/74140-P2UTT5T4IH/'; function getFinalUrl($url, $maxRedirects = 10) { $ch = curl_init(); $currentUrl = $url; $redirectCount = 0; while ($redirectCount < $maxRedirects) { curl_setopt($ch, CURLOPT_URL, $currentUrl); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HEADER, true); $response = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); // 优先处理HTTP层面的3xx重定向 if (in_array($httpCode, [301, 302, 303, 307, 308])) { preg_match('/Location:\s*(.*?)\s*$/i', $response, $matches); if (isset($matches[1])) { $currentUrl = trim($matches[1]); $redirectCount++; continue; } } // 解析meta refresh跳转 if (preg_match('/<meta[^>]+http-equiv="refresh"[^>]+content="\d+;\s*url=([^"]+)"[^>]*>/i', $response, $metaMatches)) { $currentUrl = trim($metaMatches[1]); $redirectCount++; continue; } // 解析JS代码跳转 if (preg_match('/window\.location(?:\.href)?\s*=\s*["\']([^"\']+)["\']/i', $response, $jsMatches)) { $currentUrl = trim($jsMatches[1]); $redirectCount++; continue; } // 无更多跳转,退出循环 break; } curl_close($ch); return $currentUrl; } $finalUrl = getFinalUrl($url); var_dump($finalUrl);
内容的提问来源于stack exchange,提问作者Gabriel Philipe S.
相关产品推荐
相关产品推荐

