在php中读取远程文件

时间:2015-07-22 19:21:13

标签: php

我想在我的网站上显示远程文件的内容(另一台服务器上的文件)。

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

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

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

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

它显示以下错误:

301移动

该文件已移至here 224

我只收到此错误的远程文件,本地文件显示没有问题。

有没有解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:8)

选项1 - 卷曲

使用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);

?>

选项2 - file_get_contents

根据PHP Documentation 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;
    }

?>
相关问题