In one of our projects there is the possibility of writing plug-ins 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 of us accidentally shabby.
There are a number of tools for executing PHP code in a secure environment: running in a separate process, saving code in a file and calling through cli with reduced capabilities or using specialized extensions for PHP.
Due to the specifics of the service and applications as well as to enable the use of a sandbox on all operating systems (the processes and extensions for the sandbox do not work in Windows) a small class was written with the basic PHP settings:
Ext_Sandbox_PHPValidator .
Short class description
Inside there are only two functions:
- static function php_syntax_error ($ code, $ tokens = null)
- static function validatePHPCode ($ source, $ functions = array (), $ enable = true)
php_syntax_error
The function checks if the syntax of the PHP code is correct (if parentheses, etc. are not skipped)
$ code - php code (without <? php)
$ tokens is an optional parameter, you can pass it if you have already parsed the code into tokens (you can
parse 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 will return
false .
validatePHPCode
The function checks the php code and returns the result of the check (true or false).
$ source - php code without <? php at the beginning
$ functions - allowed / prohibited functions
$ enable - boolean, if true, then $ functions will contain a list of allowed functions, if false - a list of prohibited functions.
Example:
<?php require 'PHPValidator.php'; $code = <<<PHP \$b = 1; \$c = 2; \$a = \$b + \$c; echo \$a; class test { public function __construct() { echo 'construct'; } public function foo(\$num) { var_dump(\$num); } } \$test = new test(); \$test->foo(\$a); PHP;
')
Try it online:
http://ideone.com/e1qx28The class is on github.