Retrieving Forwarded URL Content | curl and contexts

I am using file_get_contents as such

file_get_contents( $url1 ).

However, the actual contents of the URL come 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.

+3
source share
3 answers

I believe that 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);

$ meta should include, among other things, a status code and a Location header used to store the redirect URL. If $ meta points to 200, you can get the data with:

$meta = stream_get_contents($stream)

The downside is when you get 301/302, you need to configure the request again using the URL from the Location header. Wet, rinse, repeat.

+1
source

url, JS window.location.hostname

+1

I do not understand why you need PHP or JavaScript. I mean ... they are slightly different from the approach to the problem.

Assuming you want to use a server side PHP solution, there is 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 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;
}
+1
source

All Articles