我在远程服务器上使用php文件的输出,在我自己的网站上显示内容。我无权修改远程服务器上的文件。
远程php文件输出的java脚本如下:
document.write('<p>some text</p>');
如果我在浏览器中输入url,我会得到正确的输出。例如:
https://www.remote_server.com/files/the.php?param1=12
我可以在我的网站上显示远程文件的输出,如下所示:
<script type="text/javascript" src="https://www.remote_server.com/files/the.php?param1=12"></script>
但在显示输出之前,我想先过滤一下。因此,我用以下代码实现了一个php文件:
function getRemoteOutput(){
$file = fopen("https://www.remote_server.com/files/the.php?param1=12","r");
$output = fread($file,1024);
fclose($file);
return $output;
}
当我调用这个函数时,fopen()返回一个有效的句柄,但fread()返回了一个空字符串。我尝试过使用file_get_contents(),但得到了相同的结果。
我想做的事情可能吗
远程服务器是否可以允许我通过浏览器读取文件,但阻止对php文件的访问?
您的变量$output
仅包含url的前1024个字节。。。(可能是标题?)。您需要添加一个while
而不是"文件末尾"循环来连接整个远程文件。
PHP参考:feof
您可以在fread
函数的PHP描述中了解更多信息。
PHP参考:fread。
<?php
echo getRemoteOutput();
function getRemoteOutput(){
$file = fopen("http://php.net/manual/en/function.fread.php","r");
$output = "";
while (!feof($file)){ // while not the End Of File
$output.= fread($file,1024); //reads 1024 bytes at a time and appends to the variable as a string.
}
return $output;
fclose($file);
}
?>
关于您的问题:
我想做的事情可能吗?
是的,这是可能的。
远程服务器是否允许我通过浏览器,但阻止从php文件访问?
我对此表示怀疑。
我联系了我试图连接到的网站的支持团队。他们告诉我,他们确实阻止了php文件的访问。所以这似乎就是我问题的原因,显然我就是做不到我想做的事情
值得一提的是,以下是我用来测试读取文件输出的各种方法的代码:
<?php
//$remotefile = 'http://www.xencomsoftware.net/configurator/tracker/ip.php';
$remotefile = "http://php.net/manual/en/function.fread.php";
function getList1(){
global $remotefile;
$output = file_get_contents($remotefile);
return htmlentities($output);
}
function getList2(){
global $remotefile;
$file = fopen($remotefile,"r");
$output = "";
while (!feof($file)){ // while not the End Of File
$output.= fread($file,1024); //reads 1024 bytes at a time and appends to the variable as a string.
}
fclose($file);
return htmlentities($output);
}
function getList3(){
global $remotefile;
$ch = curl_init(); // create curl resource
curl_setopt($ch, CURLOPT_URL, $remotefile); // set url
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //return the transfer as a string
$output = curl_exec($ch); // $output contains the output string
curl_close($ch); // close curl resource to free up system resources
return htmlentities($output);
}
function getList4(){
global $remotefile;
$r = new HttpRequest($remotefile, HttpRequest::METH_GET);
try {
$r->send();
if ($r->getResponseCode() == 200) {
$output = $r->getResponseBody();
}
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "'n";
}
return htmlentities($output);
}
function dumpList($ix, $list){
$len = strlen($list);
echo "<p><b>--- getList$ix() ---</b></p>";
echo "<div>Length: $len</div>";
for ($i = 0 ; $i < 10 ; $i++) {
echo "$i: $list[$i] <br>";
}
// echo "<p>$list</p>";
}
dumpList(1, getList1()); // doesn't work! You cannot include/requre a remote file.
dumpList(2, getList2());
dumpList(3, getList3());
dumpList(4, getList4());
?>