3

I'm using file_get_contents as such

file_get_contents( $url1 ).

However the actual url's contents are coming from $url2.

Here is a specific case:

$url1 = gmail.com

$url2 = mail.google.com

I need a way to grab $url2 progrmatically in PHP or JavaScript.

  • You can't, not with a plain-jane file_get_contents call. – Marc B May 24 '12 at 22:09
  • 1
    If there's an actual http 30x redirect taking place, you can trap that using cURL. If it's a purely server-side action, it's invisible to you and impossible to check. – Marc B May 24 '12 at 22:11
  • Curl doesn't follow redirects unless you tell it to, so you can manually analyse the headers from each response and do the following yourself. – Marc B May 24 '12 at 22:15

3 Answers3

1

If your looking to pull the current url, in JS you can use window.location.hostname

AJak
  • 3,863
  • 1
  • 19
  • 28
1

I believe you can do this by creating a context with:

$context = stream_context_create(array('http' =>
    array(
        'follow_location'  => false
    )));
$stream = fopen($url, 'r', false, $context);
$meta = stream_get_meta_data($stream);

The $meta should include (among other things) the status code and the Location header used to hold the redirection url. If $meta indicates a 200, the you can fetch the data with:

$meta = stream_get_contents($stream)

The down side is when you get a 301/302, you have to set up the request again with the url from the Location header. Lather, rinse, repeat.

Devon_C_Miller
  • 16,248
  • 3
  • 45
  • 71
1

I don't get why you would want either PHP or JavaScript. I mean... they are kind of different in approaching the problem.

Assuming you want a server-side PHP solution, there's a comprehensive solution here. Too much code to copy verbatim but:

function follow_redirect($url){
  $redirect_url = null;

  //they've also coded up an fsockopen alternative if you don't have curl installed
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_HEADER, true);
  curl_setopt($ch, CURLOPT_NOBODY, true);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);

  //extract the new url from the header
  $pos = strpos($response, "Location: ");
  if($pos === false){
    return false;//no new url means it's the "final" redirect
  } else {
    $pos += strlen($header);
    $redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
    return $redirect_url;
  }
}

//output all the urls until the final redirect
//you could do whatever you want with these
while(($newurl = follow_redirect($url)) !== false){
  echo $url, '<br/>';
  $url = $newurl;
}
Oleg
  • 24,465
  • 8
  • 61
  • 91
  • Good info. Pros and Cons between using curl and using fopen with a context set? –  May 25 '12 at 15:42
  • http://stackoverflow.com/questions/2296508/what-are-the-biggest-differences-between-fopen-and-curl – Oleg May 26 '12 at 01:17