How do I get the final, redirected, canonical URL of a website using PHP?

前端 未结 3 471
无人及你
无人及你 2021-02-07 15:49

In the days of link shorteners and Ajax, there can be many links that ultimately point to the same content. I was wondering what the best way is to get the final, best link for

3条回答
  •  情话喂你
    2021-02-07 16:38

    Using Guzzle (a well known and robust HTTP client) you can do it like that:

    addSubscriber($history);
    
        $response = $client->head($url)->send();
    
        if (!$response->isSuccessful()) {
            throw new \Exception(sprintf("Url %s is not a valid URL or website is down.", $url));
        }
    
        return $response->getEffectiveUrl();
    }
    

提交回复
热议问题