PhpSandbox\PHPSandbox::execute PHP Method

execute() public method

This function validates your code and automatically whitelists it according to your specified configuration, then executes it.
public execute ( callable | string $callable = null, boolean $skip_validation = false ) : mixed
$callable callable | string Callable or string of PHP code to prepare and execute within the sandbox
$skip_validation boolean Boolean flag to indicate whether the sandbox should skip validation of the pass callable. Default is false.
return mixed The output from the executed sandboxed code
    public function execute($callable = null, $skip_validation = false)
    {
        $this->execution_time = microtime(true);
        $this->memory_usage = memory_get_peak_usage();
        if ($callable !== null) {
            $this->prepare($callable, $skip_validation);
        }
        $saved_error_level = null;
        if ($this->error_level !== null) {
            $saved_error_level = error_reporting();
            error_reporting(intval($this->error_level));
        }
        if (is_callable($this->error_handler) || $this->convert_errors) {
            set_error_handler([$this, 'error'], $this->error_handler_types);
        }
        if ($this->time_limit) {
            set_time_limit($this->time_limit);
        }
        $exception = null;
        $result = null;
        try {
            if ($this->capture_output) {
                ob_start();
                eval($this->generated_code);
                $result = ob_get_clean();
            } else {
                $result = eval($this->generated_code);
            }
        } catch (\Exception $exception) {
            //swallow any exceptions
        }
        if (is_callable($this->error_handler) || $this->convert_errors) {
            restore_error_handler();
        }
        usleep(1);
        //guarantee at least some time passes
        $this->memory_usage = memory_get_peak_usage() - $this->memory_usage;
        $this->execution_time = microtime(true) - $this->execution_time;
        if ($this->error_level !== null && $this->restore_error_level) {
            error_reporting($saved_error_level);
        }
        return $exception instanceof \Exception ? $this->exception($exception) : $result;
    }

Usage Example

Esempio n. 1
0
 /**
  * Test whether sandbox disallows violating callbacks
  */
 public function testWhitelistMagicConstants()
 {
     $this->sandbox->whitelistMagicConst('DIR');
     $this->assertEquals(str_replace('tests', 'src', __DIR__), $this->sandbox->execute(function () {
         return __DIR__;
     }));
 }
All Usage Examples Of PhpSandbox\PHPSandbox::execute
PHPSandbox