0

I'm trying to get page content by URL (e.g. 'http://example.com/page.html') using PHP, but remote server redirects it to another page (e.g. 'http://example.com/another-page.html') and when I try to execute code:

$p = file_get_contents('http://example.com/page.html');
echo $p;

browser returns 404 error:

The requested URL /another-page.html was not found on this server.

As I understand, instead of getting 'http://example.com/another-page.html', PHP tries to return 'another-page.html' from my localhost and of course there is no such page. Seems like remote server redirects using local address ('/another-page.html' instead of 'http://example.com/another-page.html') which is correct of course, but I don't know how to deal with it.

Could anybody advise me, how could I solve this problem?

Thanks in advance

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
Dmitriy Vinokurov
  • 365
  • 1
  • 6
  • 28
  • 2
    You could use CURL: http://stackoverflow.com/questions/4323985/how-to-get-the-real-url-after-file-get-contents-if-redirection-happens some benefits: timeout-time and more information about redirect – Kevin van Hoorn Feb 11 '14 at 11:32
  • 1
    I cannot reproduce, even with a technically invalid `Location:` header that uses relative paths. What's your PHP version? – Álvaro González Feb 11 '14 at 11:34
  • @KevinvanHoorn - PHP stream wrappers support that stuff as well. – Álvaro González Feb 11 '14 at 11:40
  • @ÁlvaroG.Vicario - php 5.5.3+dfsg-1ubuntu2.1 – Dmitriy Vinokurov Feb 11 '14 at 11:44
  • ÁlvaroG.Vicario, KevinvanHoorn - thanks, I'll try both CURL and PHP stream wrappers. – Dmitriy Vinokurov Feb 11 '14 at 11:46
  • Works fine for me on PHP/5.5.9 (Win). I've even tried with PHP/5.3.0. Are you 100% sure that such `/another-page.html` belongs to your local default site? Can you create the page manually and get redirected to it? (BTW, you are already using stream wrappers, that's why `file_get_contents` actually works even though there's no *file*.) – Álvaro González Feb 11 '14 at 11:55

0 Answers0