php - 获取最终重定向 URL

标签 php curl

特定网址:

https://www.novelupdates.com/extnu/3475538/

重定向至:

https://chrysanthemumgarden.com/novel-tl/dylm/dylm-71/

如何通过 PHP 获取最终的重定向 URL?

到目前为止我尝试过的内容

这是获取最终 URL 的命令行:

curl -Ls -w %{url_effective} -o /dev/null https://www.novelupdates.com/extnu/3475538/

不适用于此特定网址

测试了这个的 PHP 版本,但仍然没有得到最终的 URL:

$url = 'https://www.novelupdates.com/extnu/3475538/'; 

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 

// Return follow location true 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
$html = curl_exec($ch); 

// Getinfo or redirected URL from effective URL 
$redirectedUrl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); 

curl_close($ch); 
echo "Original URL:   " . $url . "<br/>"; 
echo "Redirected URL: " . $redirectedUrl . "<br/>"; 

最佳答案

我也遇到过同样的问题。应用自定义 userAgent 对我来说很有效。 感谢这篇文章:CURLOPT_FOLLOWLOCATION not working .

curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
<?php

    $original_url = 'http://www.novelupdates.com/extnu/3475538/';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $original_url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");

    $a = curl_exec($ch);
    $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

    echo "Old: ${original_url}\n";
    echo "New: ${url}\n";
Old: http://www.novelupdates.com/extnu/3475538/
New: https://chrysanthemumgarden.com/novel-tl/dylm/dylm-64/

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

相关文章:

php - 在 DOMPDF 中打印边距

php - MySQL 1 到多。仅显示第一个表中的 1 个结果

php - 如何使用 cURL 获取受 .htpasswd 保护的 URL 的 HTTP 代码?

python - 异常值 : HTTP Error 400: Bad Request after a Python/urllib2 request to PayPal Sandbox Site

PHP cURL 使用 IP 地址而不是域名连接

php - AJAX 函数在同一页面显示动态数据

php - Android应用程序的用户身份验证

php - Azure Key Vault 和托管身份 - 使用 REST 进行本地开发

c - Ubuntu - #include <curl/curl.h> 没有这样的文件或目录

php - 从 cURL 获取内容类型