Imri Persiado
Imri Persiado

Reputation: 1889

Copying a file content to a variable

I would like to copy a php file content to a variable and execute it, not print it! I found out that there are 2 ways:

file_get_contents('http://YOUR_HOST/YOUR/FILE.php');

In that way the code is executed but not as I want to, I will explain:

a.php:

<?php
require 'file.php';
$output = file_get_contents('http://example.com/b.php');
echo $output;
?>

b.php:

<?php
$hello = get_welcome_text();
echo $hello;
?>

When I execute file a.php I get the Call to undefined function error, I have no idea why it doesn't recognize the require line it seems like it executes b.php separately.

The other method is:

file_get_contents('path/to/YOUR/FILE.php');

This method is just print the php script instead of executing it.

So I would like to know if there is a way to copy a php file content into a variable and execute it the same way as include/require does, and please don't suggest me to use include/require because it's not what I'm looking for. thanks!

Upvotes: 0

Views: 1941

Answers (2)

shomeax
shomeax

Reputation: 865

In first 'method' server executes separare request for your file_get_contents, so no environment from calling script will be available inside it.

Use second 'method' to get contents of the script and then just eval it.

eval(file_get_contents('http://.../b.php.txt'));

File evaluated that way can define new functionality to be plugged in calling script so that you can call some method and/or pass parameters from it.

a.php

$r = eval(file_get_contents('http://.../b.php.txt'));
if ($r) b_foo($bar);

b.php

function b_foo($baz) {
return 42;
}
return true; // module loaded ok

Surely you know that executing unverified code from third parties in server context is a bad practice, but if you really need it... :)

Upvotes: 0

fuxia
fuxia

Reputation: 63566

Files can return a value, so yes, you can use include.

included.php:

<?php
return 2 + 2;

parent.php:

<?php
$number = include 'included.php';
echo $number;

Upvotes: 1

Related Questions