php - PHP 中用户提供的正则表达式的清理

标签 php regex sanitization

我想创建一个网站,用户可以在其中测试正则表达式(已经有很多网站了……例如这个:http://www.pagecolumn.com/tool/pregtest.htm)。基本上,用户提供一个正则表达式和一些示例文本,然后返回正则表达式评估的结果。

我想用 PHP“preg_*”函数在服务器端评估正则表达式。有没有办法清理提供的正则表达式?我应该关注哪些安全漏洞?

最佳答案

我认为 PHP 本身会检查正则表达式。 这是我制作的示例脚本:

// check for input, and set max size of input
if(@!empty($_POST['regex'])
    && @!empty($_POST['text'])
    && strlen($_POST['regex'])<1000
    && strlen($_POST['text'])<2000
    ){
    // set script timeout in case something goes wrong (SAFE MODE must be OFF)
    $old_time=ini_get('max_execution_time');
    if(!set_time_limit(1)) die('SAFE MODE MUST BE OFF'); // 1 sec is more then enough

    // trim input, it's up to you to do more checks
    $regex=trim($_POST['regex']);
    // don't trim the text, it can be needed
    $input=$_POST['text'];
    // escape slashes
    $regex=preg_replace('/([\\/]+)?//', '\/', $regex);

    // go for the regex
    if(false===$matched=@preg_match('/'.$regex.'/', $input, $matches)){
            // regex was tested, show results
            echo 'Matches: '.$matched.'<br />';
            if($matched>0){
                    echo 'matches: <br />';
                    foreach($matches as $i =>  $match){
                            echo $i.' = '.$match.'<br />';
                }
            }
    }
    // set back original execution time
    set_time_limit($old_time);
}

无论如何,永远不要对用户提交的字符串使用 eval()

此外,您可以进行一些简单的极简 sanitizer ,但这取决于您。 ;)

关于php - PHP 中用户提供的正则表达式的清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2371445/

相关文章:

php - PDO MySQL 与 PHP Usort

regex - 在 JSTL 中解析请求 URL

python - Python中将字符串数据按照自定义顺序拆分为关键字,并单独存储特定关键字

php - Propel ORM - UNION 查询

php - 将数据库记录分解为表格格式

PHP:爆炸数组

python - 提取搜索词周围的词

html - pdo 在服务器上插入清理 html,而不是在本地

css - 从 enavto 主题检查插件收到有关自定义 css 的警告

php - 我需要清理 file_exists 的输入吗?