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

前端 未结 3 482
无人及你
无人及你 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:28

    I wrote you a little function to do it. It's simple, but it may be a starting point for you. Note: the http://dlvr.it/xxb0W url returns an invalid URL for it's Location response header.

    You'll need the Altumo PHP library for it to work. It's a library that I wrote, but it's MIT license, as is this function.

    See: https://github.com/homer6/altumo

    Also, you'll have to wrap the function in a try/catch.

    /**
    * Gets the final URL of a URL that will be redirected.
    * 
    * @param string $url_string
    * @throws \Exception                    //on error
    * @return string
    */
    function get_final_url( $url_string ){
    
        while( 1 ){
    
            //validate URL
                $url = new \Altumo\String\Url( $url_string );
    
            //get the Location response header of the URL
                $client = new \Altumo\Http\OutgoingHttpRequest( $url_string );
                $response = $client->sendAndGetResponseMessage();
                $location = $response->getHeader( 'Location' );
    
            //return the URL if no Location header was found, else continue
                if( is_null($location) ){
                    return $url_string;
                }else{
                    $url_string = $location;
                }
    
        }
    
    }
    
    echo get_final_url( 'your url here' );
    

    Please let me know if you'd like further modifications or help getting it going.

提交回复
热议问题