Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will PHPs fopen follow 301 redirects?

We have a piece of legacy code that (ab)uses fopen() calls to resources over HTTP:

@fopen('http://example.com')

We want to move example.com to another host and then send "301 Permanently Moved", however, we are not entirely sure if @fopen() will follow this.

Initial tests show me that it does not. But maybe I miss some configuration piece.

like image 299
berkes Avatar asked Jul 20 '10 11:07

berkes


1 Answers

Since version 5.1.0, there's the max_redirects option, which makes the fopen HTTP wrapper follow the Location redirect:

The max number of redirects to follow. Value 1 or less means that no redirects are followed.

Defaults to 20.

You might want to set it explicitly, in case your config disables this. An example modified from the docs:

<?php

$url = 'http://www.example.com/';

$opts = array(
       'http' => array('method' => 'GET',
                       'max_redirects' => '20')
       );

$context = stream_context_create($opts);
$stream = fopen($url, 'r', false, $context);

// header information as well as meta data
// about the stream
var_dump(stream_get_meta_data($stream));

// actual data at $url
var_dump(stream_get_contents($stream));
fclose($stream);
?>
like image 150
Piskvor left the building Avatar answered Sep 28 '22 19:09

Piskvor left the building