【问题标题】:Will PHPs fopen follow 301 redirects?PHPs fopen 会遵循 301 重定向吗?
【发布时间】:2011-03-18 09:44:04
【问题描述】:

我们有一段遗留代码 (ab) 使用 fopen() 通过 HTTP 调用资源:

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

我们想将 example.com 移动到另一个主机,然后发送“301 Permanently Moved”,但是,我们不完全确定 @fopen() 是否会遵循此操作。

最初的测试告诉我它没有。但也许我错过了一些配置。

【问题讨论】:

  • 我预见到你的未来会重构!
  • 当然。这个重定向实际上是这个重构的第一步:)

标签: php http sockets redirect http-status-code-301


【解决方案1】:

从 5.1.0 版开始,有了 max_redirects option,这使得 fopen HTTP 包装器遵循 Location 重定向:

要遵循的最大重定向数。值 1 或更少表示不遵循重定向。

默认为 20。

您可能需要明确设置它,以防您的配置禁用它。从文档修改的示例:

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

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    相关资源
    最近更新 更多