php get final redirect url

Solutions on MaxInterview for php get final redirect url by the best coders in the world

showing results for - "php get final redirect url"
Alice
27 Sep 2016
1/**
2 * get_redirect_url()
3 * Gets the address that the provided URL redirects to,
4 * or FALSE if there's no redirect. 
5 *
6 * @param string $url
7 * @return string
8 */
9function get_redirect_url($url){
10    $redirect_url = null; 
11
12    $url_parts = @parse_url($url);
13    if (!$url_parts) return false;
14    if (!isset($url_parts['host'])) return false; //can't process relative URLs
15    if (!isset($url_parts['path'])) $url_parts['path'] = '/';
16
17    $sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80), $errno, $errstr, 30);
18    if (!$sock) return false;
19
20    $request = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n"; 
21    $request .= 'Host: ' . $url_parts['host'] . "\r\n"; 
22    $request .= "Connection: Close\r\n\r\n"; 
23    fwrite($sock, $request);
24    $response = '';
25    while(!feof($sock)) $response .= fread($sock, 8192);
26    fclose($sock);
27
28    if (preg_match('/^Location: (.+?)$/m', $response, $matches)){
29        if ( substr($matches[1], 0, 1) == "/" )
30            return $url_parts['scheme'] . "://" . $url_parts['host'] . trim($matches[1]);
31        else
32            return trim($matches[1]);
33
34    } else {
35        return false;
36    }
37
38}
39
40/**
41 * get_all_redirects()
42 * Follows and collects all redirects, in order, for the given URL. 
43 *
44 * @param string $url
45 * @return array
46 */
47function get_all_redirects($url){
48    $redirects = array();
49    while ($newurl = get_redirect_url($url)){
50        if (in_array($newurl, $redirects)){
51            break;
52        }
53        $redirects[] = $newurl;
54        $url = $newurl;
55    }
56    return $redirects;
57}
58
59/**
60 * get_final_url()
61 * Gets the address that the URL ultimately leads to. 
62 * Returns $url itself if it isn't a redirect.
63 *
64 * @param string $url
65 * @return string
66 */
67function get_final_url($url){
68    $redirects = get_all_redirects($url);
69    if (count($redirects)>0){
70        return array_pop($redirects);
71    } else {
72        return $url;
73    }
74}
75