gpt4 book ai didi

php - 使用 Curl PHP 获取最终重定向

转载 作者:行者123 更新时间:2023-12-03 23:31:31 26 4
gpt4 key购买 nike

我必须从中获取最终的重定向 url:https://web.archive.org/web/20070701005218/http://www.maladnews.com/实际上重定向到这个:https://web.archive.org/web/20080109064420/http://www.maladnews.com/Site%203/Malad%20City%20&%20Oneida%20County%20News/Malad%20City%20&%20Oneida%20County%20News.html

我尝试了其他 stackoverflow 答案中的答案,这些答案适用于其他网站,但不适用于上述链接。

我试图提取常规位置 header :

if(preg_match('#Location: (.*)#', $html, $m))
$l = trim($m[1]);

并检查了javascript方式:
preg_match("/window\.location\.replace\('(.*?)'\)/", $html, $m) ? $m[1] : null;

请帮忙!

最佳答案

使用 curl_getinfo() CURLINFO_REDIRECT_URLCURLINFO_EFFECTIVE_URL取决于您的用例。

CURLINFO_REDIRECT_URL - With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL



-- http://php.net/manual/en/function.curl-getinfo.php

例子:
<?php
$url = 'https://google.com/';

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

$html = curl_exec($ch);

$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

curl_close($ch);

echo "Original URL: " . $url . "\n";
echo "Redirected URL: " . $redirectedUrl . "\n";

当我运行此代码时,输​​出为:
Original URL:   https://google.com/
Redirected URL: https://www.google.com/

关于php - 使用 Curl PHP 获取最终重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com