📜 ⬆️ ⬇️

PHP Sandbox

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:

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; // validate the code $validator = new Ext_Sandbox_PHPValidator(); try { // 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: http://ideone.com/e1qx28

The class is on github.

Source: https://habr.com/ru/post/179645/


All Articles