Search code examples
phpreadfilefread

How to use fread (or readfile) function (PHP) to get the output result of another PHP page?


Summary

I am trying to use fread (or readfile) function (PHP) to get the output result of another PHP page. For example, I want to read (or even download as another file to my PC) the output result of the page “add.php?a=1&b=4”. Below is the PHP codes.

Code

read.php

<?php
$filename = "add.php?a=1&b=4";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
echo $contents;        //I hope it can output “5” (the output result of the page “add.php?a=1&b=4”)
fclose($handle);
?>

add.php

<?php
echo $_GET["a"]+$_GET["b"];
?>

Below is the example of the readfile function. I want to download the output result of the page “add.php?a=1&b=4” as the file "result.txt". But it doesn't work either.

readfile.php

<?php
header("Content-type:application");
header("Content-Disposition: attachment; filename=result.txt"); 
readfile("add.php?a=1&b=4");
?>

How can I modify it?


Solution

  • If you want to read the web output, you need to read it through the HTTP server.

    <?php
    header("Content-type:application");
    header("Content-Disposition: attachment; filename=result.txt");
     echo file_get_contents("http://yourserver.example.com/add.php?a=1&b=4");