简体   繁体   中英

Reading remote files using PHP

can anyone tell me how to read up to 3 remote files and compile the results in a query string which would now be sent to a page by the calling script, using headers.

Let me explain:

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)

You may be able to use file_get_contents , then make sure you urlencode the data when you construct the redirection url

$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));

Also note this URL should be kept under 2000 characters .

Want to send more than 2000 chars?

If you want to utilize more data than 2000 characters would allow, you will need to POST it. One technique here would be to send some HTML back to the client with a form containing your data, and have javascript automatically submit it when the page loads.

The form could have a default button which says "Click here to continue..." which your JS would change to "please wait...". Thus users without javascript would drive it manually.

In other words, something like this:

<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 certainly helps, but for remote scripting CURL is better options.

This works well even if allow_url_include = On (in your 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);

You can use the file_get_contents function. API documentation: http://no.php.net/manual/en/function.file-get-contents.php

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

Do note that if the file contain multiple lines or very, very long lines you should contemplate using HTTP post instead of a long URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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