It's important to stress that including/executing user-generated code is dangerous. Using a system call (exec
, shell_exec
, system
) instead of include
helps separate the execution context, but it's not much safer. Consider proper sanitation or sand-boxing.
With that in mind, here is a working example including generating the (temporary) file, executing it, and cleanup:
<?php
// test content
$code = <<<PHP
echo "test";
PHP;
// create temporary file
$d=rand();
$myfile="$d.php";
file_put_contents($myfile,"<?php\n$code\n?>");
// start capture output
ob_start();
// include generate file
// NOTE: user-provided code is unsafe, they could e.g. replace this file.
include($myfile);
// get capture output
$result = ob_get_clean();
// remove temporary file
unlink($myfile);
// output result
echo "================\n" . $result . "\n================\n" ;
Output:
================
test
================