且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Curl PHP获取最终重定向

更新时间:2023-11-26 16:45:22

使用 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/