file_get_contents() PHP 函数的正确使用方法

Proper way of using file_get_contents() PHP function

我在使用 file_get_contents() 函数时遇到一些问题:如果远程文件重定向到另一个 URI,我会遇到脚本中断和脚本输出重复的问题:

代码:

$context = stream_context_create(['http'=>['timeout'=>10]]);
$url = 'http://example.com/';
echo "URL: $url\n";
$page = file_get_contents($url,FALSE,$context);
echo "Page size: ".strlen($page);

输出:

URL: http://example.com/
URL: http://example.com/

(请注意输出重复并且没有 "Page size" 输出)

预期输出:

URL: http://example.com/
Page size: 1000

我认为 file_get_contents() 无法处理重定向,如果我在浏览器中尝试 URL 就可以看到。所以我想实现以下目标之一:

  1. 抓住错误就能处理的情况

  2. 加载页面尽管重定向

也许我可以为 $context 添加更多选项?或者 only 方法是移动到 curl?

file_get_contents() 的错误用法: http://php.net/manual/en/function.file-get-contents.php 第三个参数应该是 $context

有许多很棒的库从 PHP 中提取 curl 处理问题。我个人喜欢 Guzzle 和 Request。您可以找到指向该库的链接 here.

也就是说,您的脚本中确实存在语法错误,因为 $contextfile_get_content() 的第三个参数。

应该是:

$page = file_get_contents($url, false, $context);

你可以通过extra options to your stream_context_create。默认情况下它遵循重定向,20 是放弃前的最大重定向次数。

您确定 URL 在您的浏览器中加载时不会使用 JS 进行重定向吗?