crisu83/php-expression

一个用于安全评估PHP表达式的简易库。

dev-master 2013-07-22 14:50 UTC

This package is auto-updated.

Last update: 2024-08-29 03:15:46 UTC


README

一个用于安全评估PHP表达式的简易库。

我为什么需要这个?

有时你无法避免在PHP中使用eval,例如当你有一个使用PHP表达式和其业务规则的规则引擎时。当你需要使用eval时,你希望有一个安全的环境来做这件事,这就是php-expression的作用。使用php-expression,你可以检查语法,在评估之前安全地测试你的表达式,并捕获可能发生的异常。默认情况下,php-expression不允许使用任何语言构造或函数,但你可以配置它以允许你想要的一切。

如何使用它?

<?php

// Require the library files.
// Alternatively you can require it using Composer (https://getcomposer.org.cn/).
require(__DIR__ . '/path/to/php-expression/Expression.php');
require(__DIR__ . '/path/to/php-expression/Exception/Fatal.php');
require(__DIR__ . '/path/to/php-expression/Exception/NotSafe.php');
require(__DIR__ . '/path/to/php-expression/Exception/Runtime.php');
require(__DIR__ . '/path/to/php-expression/Exception/Syntax.php');

// Define an example class that we will use in this example.
class Test
{
  public function foobar()
  {
    return 'foobar';
  }
}

// This is code that we will run through the expression object.
$code = '$test = new Test; return $test->foobar();';

// Create a new expression for the code above.
$exp = new \Crisu83\PhpExpression\Expression($code);

// Allow the 'new' keyword to be used in the expression.
$exp->setAllowedKeywords(array('new', 'return'));

// Allow the class 'Test' to be used in the expression.
$exp->setAllowedClassNames(array('Test'));

// Allow the method 'foobar' to be called in the expression.
$exp->setAllowedFunctions(array('foobar'));

// Evaluate the code and catch any exceptions that may occur.
$result = null;
try {
  $result = $exp->evaluate();
} catch (Exception $e) {
  // In this example we just print the error message.
  echo $e->getMessage();
}

// Output the result which is 'foobar'.
echo $result;