Will PHPs fopen follow 301 redirects?

旧时模样 提交于 2019-12-08 19:18:00

问题


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.


回答1:


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);
?>


来源:https://stackoverflow.com/questions/3289615/will-phps-fopen-follow-301-redirects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!