Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Is there a way to "include" a string as a file?

Tags:

include

php

There is a known way to include a file and capture its contents into a string while loading.

$string = get_include_contents('somefile.php');
function get_include_contents($filename) {
if (is_file($filename)) {
        ob_start();
        include $filename;
        return ob_get_clean();
    }
    return false;
}

https://www.php.net/manual/en/function.include.php

Is there a way to "include" contents loading them from a string instead of a file?

I mean something like this:

$string = file_get_contents("file.php");
include_from_string($string);
like image 379
Galileo Avatar asked Mar 20 '23 18:03

Galileo


1 Answers

If you want the string to be parsed as PHP code, just like the contents of a file loaded with include(), then the function you need is eval().

Note that, unlike code loaded by include(), code executed by eval() automatically starts in PHP mode, so you don't need to (and shouldn't!) prefix it with <?php. If you want to emulate the behavior of include() exactly, you can prefix the string to be eval()ed with ?> to leave PHP mode:

$string = file_get_contents( 'somefile.php' );
eval( '?>' . $string );

Also note that eval() is a very dangerous function to play with! While in this specific case it shouldn't be any more risky than include() itself is, using eval() on any string that might even possibly contain unsanitized (or insufficiently sanitized) user input is extremely dangerous, and may be exploited by attackers to execute malicious code on your system and thereby gain control of it.

like image 103
Ilmari Karonen Avatar answered Apr 02 '23 15:04

Ilmari Karonen