简体   繁体   中英

“file_get_contents” does not work as expected

I setup a function to get the output of another page. But i am only getting back the file contents. I cant figure out why? Here is my code:

$from = date('d.m.Y');
        $to = date('d.m.Y', strtotime('+30 day', time()));
        $postdata = http_build_query(
            array(
                'set' => $from,
                'to' => $to
            )
        );       
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'header'  => 'Content-type: application/x-www-form-urlencoded',
                'content' => $postdata
            )
        );   
        $context  = stream_context_create($opts);   
        $list = file_get_contents($_SERVER['DOCUMENT_ROOT'] . 'Events.php', false, $context);

file_get_contents() on filesystem will read the file as a text file. You have to call it through its uri instead to get it to execute.

it is not 1 function, but two, alternating what it does given filesystem (pretty much fopen the file, read the entirety of the file, return the content), and what it does given a url (do a GET call on the url, get its contents, return the entirety of its contents)

so just replace $_SERVER['DOCUMENT_ROOT'] with $_SERVER['HTTP_HOST'] and you should be ok

If you want to include another local php file you have to include() or require() it.

$list = include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');

While include() throws a warning if the file does not exist or is unreadable, require() throws a fatal error. With this way you get what the named file returns using the return-keyword.

To get the php output you can use ob_start():

ob_start();
include($_SERVER['DOCUMENT_ROOT'] . 'Events.php');
$list = ob_get_clean();

Another way is to use a separate http-Get but this means more overhead.

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