php 获取PHP中URL的HTTP重定向目标

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 获取PHP中URL的HTTP重定向目标相关的知识,希望对你有一定的参考价值。

<?php

// FOLLOW A SINGLE REDIRECT:
// This makes a single request and reads the "Location" header to determine the
// destination. It doesn't check if that location is valid or not.
function get_redirect_target($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $headers = curl_exec($ch);
    curl_close($ch);

    // Check if there's a Location: header (redirect)
    if (preg_match('/^Location: (.+)$/im', $headers, $matches))
        return trim($matches[1]);

    // If not, there was no redirect so return the original URL
    // (Alternatively change this to return false)
    return $url;
}

// FOLLOW ALL REDIRECTS:
// This makes multiple requests, following each redirect until it reaches the
// final destination.
function get_redirect_final_target($url)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
    curl_exec($ch);
    $target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);

    if ($target)
        return $target;

    return false;
}

以上是关于php 获取PHP中URL的HTTP重定向目标的主要内容,如果未能解决你的问题,请参考以下文章

抓取重定向的目标链接

PHP获取重定向URL的几种方法

php从源url获取重定向的url

使用curl获取Location:重定向后url

使用 php 获取 302 重定向 url

PHP CURL 跟随重定向以获取 HTTP 状态