douzhulv1699 2012-07-09 09:19
浏览 17
已采纳

通过在输入文件解析中删除eval()来保护片段

I have a template-esque system which can load bulk templates (more than one template entry in one file) and store them accordingly. The problem is that the current approach uses preg_replace() and eval and it is really error-prone. An example for this error could be an improperly-placed character which breaks the regular expression and creates a parse error:

Parse error: syntax error, unexpected '<' in tsys.php: eval()'d code

The code which does this said loading is the following:

// Escaping
$this->_buffer = str_replace( array('\\', '\'', "
"), array('\\\\', '\\\'', ''), $this->_buffer);

// Regular-expression chunk up the input string to evaluative code
$this->_buffer = preg_replace('#<!--- BEGIN (.*?) -->(.*?)<!--- END (.*?) -->#', "
" . '$this->_tstack[\'\\1\'] = \'\\2\';', $this->_buffer);

// Run the previously created PHP code
eval($this->_buffer);

An example file of this bulk template looks like the following:

<!--- BEGIN foo -->
<p>Some HTML code</p>
<!--- END foo -->

<!--- BEGIN bar -->
<h1>Some other HTML code</h1>
<!--- END bar -->

When the code is ran on this input, the $this->_tstack will be given two elements:

array (
  'foo' => "<p>Some HTML code</p>",
  'bar' => "<h1>Some other HTML code</h1>",
);

Which is the expected behavior but I am looking for a method which we could drop the need of eval.

  • 写回答

2条回答 默认 最新

  • dtwbp26022 2012-07-13 15:50
    关注

    Well, here goes. Given $template contains:

    <!--- BEGIN foo -->
        <p>Some HTML code</p>
    <!--- END foo -->
    
    <!--- BEGIN bar -->
        <h1>Some other HTML code</h1>
    <!--- END bar -->
    

    Then:

    $values = array();
    $pattern = '#<!--- BEGIN (?P<key>\S+) -->(?P<value>.+?)<!--- END (?P=key) -->#si';
    if ( preg_match_all($pattern, $template, $matches, PREG_SET_ORDER) ) {
        foreach ($matches as $match) {
            $values[$match['key']] = trim($match['value']);
        }
    }
    var_dump($values);
    

    Results in:

    array(2) {
      ["foo"]=>
      string(21) "<p>Some HTML code</p>"
      ["bar"]=>
      string(29) "<h1>Some other HTML code</h1>"
    }
    

    If white space preservation is important, remove trim().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁
  • ¥15 bywave配置文件写入失败
  • ¥20 基于Simulink的ZPW2000轨道电路仿真
  • ¥15 pycharm找不到在环境装好的opencv-python
  • ¥15 在不同的执行界面调用同一个页面
  • ¥20 基于51单片机的数字频率计
  • ¥50 M3T长焦相机如何标定以及正射影像拼接问题
  • ¥15 keepalived的虚拟VIP地址 ping -s 发包测试,只能通过1472字节以下的数据包(相关搜索:静态路由)