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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With