Sandbox for PHP

In one of our projects, it is possible to write plugins to expand the functionality of the service.
Users create application plugins in our interface and describe their logic in PHP.
It was necessary to limit the possibilities of PHP, so that no one accidentally coded us.
There are a number of tools for executing PHP code in a protected environment: execution in a separate process, saving the code in a file and calling through cli with truncated capabilities or using specialized extensions for PHP.
Due to the specifics of the service and applications, as well as the possibility of using the sandbox on all operating systems (processes and extensions for sandbox do not work on Windows), a small class was written with the basic PHP settings: Ext_Sandbox_PHPValidator .

A small description of the class

Inside there are only two functions:
  • static function php_syntax_error ($ code, $ tokens = null)
  • static function validatePHPCode ($ source, $ functions = array (), $ enable = true)


The function checks if the syntax of the PHP code is correct (whether the brackets are missing, etc.)
$ code - php code (without $ tokens - an optional parameter, you can pass it if you have already parsed the code into tokens (you can parse the code using the token_get_all function ) .
The function returns an error in the format: array (error mesage, error Line #)
If there is no error - the function returns to false .


The function checks the php code and returns the result of the check (true or false).
$ source - php code without $ functions - allowed / forbidden functions
$ enable - boolean, if true, then $ functions will contain a list of allowed functions, if false - a list of prohibited functions.


// validate the code
$validator = new Ext_Sandbox_PHPValidator();
    // we enable only one function - echo, all others will throw error
    $validator->validatePHPCode( $code, array('echo'), true);
    $status = 'passed';
catch(Exception $ex)
    $status = $ex->getMessage();
echo 'Status of validation is: ' . $status;

Try it online:

The class is on GitHub.

Also popular now: