繁体   English   中英

使用PHP读取远程文件

[英]Reading remote files using PHP

谁能告诉我如何最多读取3个远程文件并将结果编译成查询字符串,然后由调用脚本使用标头将其发送到页面。

让我解释:

page1.php

$rs_1 = result from remote page a;
$rs_2 = result from remote page b;
$rs_3 = result from remote page c;

header("Location: page2.php?r1=".$rs_1."&r2=".$rs_2."&r3=".$rs_3)

您可能可以使用file_get_contents ,然后在构造重定向URL时确保对数据进行urlencode

$rs_1 =file_get_contents($urlA);
$rs_2 =file_get_contents($urlB);
$rs_3 =file_get_contents($urlC);


header("Location: page2.php?".
  "r1=".urlencode($rs_1).
  "&r2=".urlencode($rs_2).
  "&r3=".urlencode($rs_3));

另请注意,此URL应保留2000个字符以内

要发送超过2000个字符?

如果要使用超过2000个字符允许的更多数据,则需要对其进行POST。 这里的一种技术是使用包含您的数据的表单将一些HTML发送回客户端,并让javascript在页面加载时自动提交。

表单中可能有一个默认按钮,显示“单击此处继续...”,您的JS会更改为“请稍候...”。 因此,没有javascript的用户将手动驱动它。

换句话说,是这样的:

<html>
<head>
<title>Please wait...</title>
<script>

function sendform()
{
   document.getElementById('go').value="Please wait...";
   document.getElementById('autoform').submit();
}
</script>
</head>    
<body onload="sendform()">
<form id="autoform" method="POST" action="targetscript.php">
<input type="hidden" name="r1" value="htmlencoded r1data here">
<input type="hidden" name="r2" value="htmlencoded r2data here">
<input type="hidden" name="r3" value="htmlencoded r3data here">
<input type="submit" name="go" id="go" value="Click here to continue">
</form>

</body>
</html>

file_get_contents当然有帮助,但是对于远程脚本来说,CURL是更好的选择。

即使allow_url_include = On (在您的php.ini中),这也能很好地工作

$target = "Location: page2.php?";

$urls = array(1=>'url-1', 2=>'url-2', 3=>'url-3');
foreach($urls as $key=>$url) {
    // get URL contents
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    $target .= "&r".$key."=".urlencode($output));
}
header("Location: ".$target);

您可以使用file_get_contents函数。 API文档: http : //no.php.net/manual/zh/function.file-get-contents.php

$file_contents = file_get_contents("http://www.foo.com/bar.txt")

请注意,如果文件包含多行或非常长的行,则应考虑使用HTTP发布而不是长URL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM