我想在我的网站上显示远程文件(另一台服务器上的文件)的内容。
我使用了以下代码,readfile() 函数在当前服务器上运行良好
<?php
echo readfile("editor.php");
但是当我试图获取一个远程文件时
<?php
echo readfile("http://example.com/php_editor.php");
它显示了以下错误:
301 移动
文档已移动here 224
我只收到此错误远程文件,本地文件显示没有问题。
有办法解决这个问题吗?
谢谢!
最佳答案
选项 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);
?>
选项 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;
}
?>
关于php - 在php中读取远程文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572189/