在PHP中读取远程文件

16

我希望在我的网站上展示一个远程文件的内容(另一台服务器上的文件)。

我使用了下面的代码,readfile()函数在当前服务器上正常工作。


<?php
echo readfile("editor.php");

但是当我尝试获取远程文件时

<?php
echo readfile("http://example.com/php_editor.php");

它显示了以下错误:

301 moved

该文档已移动此处224。

我只在远程文件中收到这个错误,本地文件没有问题。

有什么方法可以解决这个问题吗?

谢谢!


4
使用curl替代readfile(),并配置CURLOPT_FOLLOWLOCATION选项以处理重定向。http://php.net/manual/en/function.curl-setopt.php - Michael Berkowski
1
一个更直接的例子在https://dev59.com/yXA75IYBdhLWcg3wAUF9。 - Michael Berkowski
4
@Starkeen,你能看到你无法显示远程文件的内容,只能显示执行结果。 - splash58
2
你不能只是使用file_get_contents吗? - cantsay
1个回答

22

选项1-Curl

使用CURL并将CURLOPT_FOLLOWLOCATION选项设置为true:

<?php

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http//example.com");
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    if(curl_exec($ch) === FALSE) {
         echo "Error: " . curl_error($ch);
    } else {
         echo curl_exec($ch);
    }

    curl_close($ch);

?>

选项二 - file_get_contents

根据PHP文档file_get_contents()默认会跟随最多20个重定向。因此您可以使用该函数。如果失败,file_get_contents()将返回FALSE,否则它将返回整个文件。

<?php

    $string = file_get_contents("http://www.example.com");

    if($string === FALSE) {
         echo "Could not read the file.";
    } else {
         echo $string;
    }

?>

最好提醒OP检查file_get_contents的结果是否存在错误,例如:if($string===FALSE) { $string = "无法加载文件!"; },并且对于curl的错误也要做同样的处理。 - EdgeCaseBerg
谢谢!我已经在我的帖子中添加了这些信息。 - Emil
1
不要忘记,对于“选项2”,配置变量'allow_url_fopen'必须设置为打开状态。 - Cuse70

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接