Redirect urls how to get real url

Discussion in 'PHP' started by PinoyIto, Oct 24, 2007.

  1. #1
    PinoyIto, Oct 24, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    function get_final_location($url)
    {
    	$headers = @get_headers($url);
    	$pattern = '/Location\s*:\s*(https?:[^;\s\n\r]+)/i';
    
    	if ($locations = preg_grep($pattern, $headers))
    	{
    		preg_match($pattern, end($locations), $redirect);
    		return $redirect[1];
    	}
    
    	return $url;
    }
    
    
    PHP:
     
    nico_swd, Oct 25, 2007 IP
  3. krakjoe

    krakjoe Well-Known Member

    Messages:
    1,795
    Likes Received:
    141
    Best Answers:
    0
    Trophy Points:
    135
    #3
    
    <?php
    /**
     * @author Interviolet
     * @package [$package]
     * @filename [$filename]
     * @copyright 2007
     */
    
    if( !function_exists('get_headers') )
    {
    	function get_headers( $url, $format = 0 )
    	{
    		$host = parse_url( $url );
    		$headers = null;
    		
    		if( $host['query'] )
    			$host['path'] = sprintf( "%s?%s", $host['path'], $host['query'] );
    		
    		if( ( $socket = fsockopen( $host['host'], $host['port'] ? $host['port'] : 80 ) ) )
    		{
    			if( fwrite( $socket, sprintf( "HEAD /$host[path] HTTP/1.0\r\nConnection: close\r\n\r\n" ) ) )
    			{
    				while( !feof( $socket ) and ( $buffer = fgets( $socket ) ) )
    				{
    					if( trim( $buffer ) )
    					{
    						if( $format )
    						{
    							if( !count( $headers ) )
    							{
    								$headers[0] = trim( $buffer ) ;
    							}
    							else
    							{
    								list( $key, $value ) = explode(':', $buffer, 2 );
    								
    								$headers[ trim( $key ) ] = trim( $value );
    							}
    						}
    						else
    						{
    							$headers .= $buffer ;
    						}
    					}	
    				}
    				fclose( $socket );
    			}
    		}
    		return $headers ;
    	}
    }
    ?>
    
    PHP:
    get_headers for php4

    and also ...

    
    $head = get_headers( "http://theurlthatforwardsthebrowser.com" );
    echo $head['Location'];
    
    PHP:
     
    krakjoe, Oct 25, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    Nice one, except that get_headers() automatically redirects if there's a "Location" header and returns the headers of the new locations as well.

    In some rare cases URLs are redirected multiple times, and if that's the case, the combination of both codes would not work properly.
     
    nico_swd, Oct 25, 2007 IP
  5. PinoyIto

    PinoyIto Notable Member

    Messages:
    5,863
    Likes Received:
    170
    Best Answers:
    0
    Trophy Points:
    260
    #5


    Thanks this works perfectly....
     
    PinoyIto, Oct 25, 2007 IP