Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the real URL after file_get_contents if redirection happens?

Tags:

redirect

php

I'm using file_get_contents() to grab content from a site, and amazingly it works even if the URL I pass as argument redirects to another URL.

The problem is I need to know the new URL, is there a way to do that?

like image 546
HappyDeveloper Avatar asked Dec 01 '10 11:12

HappyDeveloper


People also ask

Does redirect Change URL?

If you need to change the URL of a page as it is shown in search engine results, we recommend that you use a permanent server side redirect whenever possible. This is the best way to ensure that Google Search and people are directed to the correct page.

How do I automatically redirect a URL?

To redirect from an HTML page, use the META Tag. With this, use the http-equiv attribute to provide an HTTP header for the value of the content attribute. The value of the content is the number of seconds; you want the page to redirect after.

How does a redirect URL work?

Typing a URL into your browser or clicking on a link sends a request for the page to the server of the website. A 301, “moved permanently,” redirect is a set of instructions which are executed when the request hits the server, automatically re-routing to a different page.


1 Answers

If you need to use file_get_contents() instead of curl, don't follow redirects automatically:

$context = stream_context_create(     array(         'http' => array(             'follow_location' => false         )     ) );  $html = file_get_contents('http://www.example.com/', false, $context);  var_dump($http_response_header); 

Answer inspired by: How do I ignore a moved-header with file_get_contents in PHP?

like image 61
Jakub Zalas Avatar answered Sep 24 '22 21:09

Jakub Zalas