fracasula / phpsandboxbundle
Symfony 2 的 PHP 沙盒工具包
dev-master
2015-02-17 13:09 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: 4.5.0
This package is not auto-updated.
Last update: 2024-09-28 17:17:49 UTC
README
使用此工具包,您可以在沙盒中或当前环境中运行 PHP 代码。否则,您可以使用它进行多任务处理,在后台运行子进程。
先决条件
此工具包需要 Symfony 2.1+。
安装
步骤 1:使用 composer 下载 PhpSandboxBundle
在您的 composer.json 中添加 PhpSandboxBundle
"require": { "fracasula/phpsandboxbundle": "dev-master" }
现在运行以下命令告诉 composer 下载工具包
$ php composer.phar update fracasula/phpsandboxbundle
Composer 将工具包安装到您的项目 vendor/fracasula
目录。
步骤 2:启用工具包
在您的 kernel 中启用工具包
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new FraCasula\Bundle\PhpSandboxBundle\FraCasulaPhpSandboxBundle(), ); }
示例
在当前环境中运行 PHP 代码
注意:共享函数、类和传播错误/异常(如 eval)
<?php class Test { public $x; } // ... inside a controller $sandbox = $this->container->get('fra_casula_php_sandbox'); $result = $sandbox->run('$test = new Test(); $text->x = 5; echo $test->x;'); echo $result; // will output 5 // or... $result = $sandbox->run('echo intval($_SANDBOX["arg1"]) * 2;', array('arg1' => '10')); echo $result; // 20
在单独的沙盒中运行 PHP 代码
注意:不共享类/函数,也不传播错误
代码在分离的进程中执行
<?php $variables = array('arg1' => '3'); $result = $sandbox->runStandalone('echo intval($_SERVER["arg1"]) * 2;', $variables); echo $result; // 6
另一个示例
<?php use FraCasula\Bundle\PhpSandboxBundle\Exception\PhpSandboxNotice; use FraCasula\Bundle\PhpSandboxBundle\Exception\PhpSandboxWarning; use FraCasula\Bundle\PhpSandboxBundle\Exception\PhpSandboxError; // ... try { $sandbox->runStandalone('$arr = array(1, 2, 3); echo $arr[100];'); } catch (PhpSandboxNotice $e) { // this will print: // [NOTICE OCCURRED] PHP Notice: Undefined offset: 100 in - on line 1 echo '[NOTICE OCCURRED] ' . $e->getMessage(); }
在后台运行 PHP 代码
注意:进程分叉,因此不共享类/函数,也不传播错误
代码在分离的子进程中执行
$sandbox->runInBackground ( 'imagecopyresized(/* ... */)', array('arg1', 'arg2'), true // TRUE means "wait for child response" | FALSE don't wait );