使用Curl PHP获取最终重定向 [英] Get final redirect with Curl PHP

查看:192
本文介绍了使用Curl PHP获取最终重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须从这里获取最终的重定向网址: 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

I have to get the final redirect url from the this: https://web.archive.org/web/20070701005218/http://www.maladnews.com/ which actually redirects to this: 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答案的答案,适用于其他网站,但不是上述链接。

I tried the answers from other stackoverflow answers which works for other websites but not for the above link.

我试图提取常规位置标题:

I've tried to extract regular location header:

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

并检查javascript方式:

and also checked the javascript way:

preg_match("/window\.location\.replace\('(.*?)'\)/", $html, $m) ? $m[1] : null;

请帮助!

推荐答案

使用 curl_getinfo() CURLINFO_REDIRECT_URL CURLINFO_EFFECTIVE_URL b
$ b

Use curl_getinfo() with CURLINFO_REDIRECT_URL or CURLINFO_EFFECTIVE_URL depending on your use case.


CURLINFO_REDIRECT_URL - 禁用 CURLOPT_FOLLOWLOCATION :在最后一个事务中找到的重定向URL,应该手动请求下一个。启用 CURLOPT_FOLLOWLOCATION 选项:此为空。此情况下的重定向网址位于 CURLINFO_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 a>

<?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";

当我运行此代码时,输​​出是:

When I run this code, the output is:

Original URL:   https://google.com/
Redirected URL: https://www.google.com/

这篇关于使用Curl PHP获取最终重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆