如何在 CodeIgniter 中转义 form_dropdown 值

How to escape the form_dropdown values in CodeIgniter

我使用 CodeIgniter 3 构建了一个网络应用程序,PHP 7.0 和 MySQL 5.6。

我有一个名为 'departments' 的 table,用户可以在应用程序上使用表单创建行。

数据库中的结果如下所示:

id    1
name  accounting

在另一种形式中,我允许用户创建一个子部门,它依赖于一个部门。我让用户在下拉菜单中选择部门。 options的name为部门名称,value为id,根据存储的数据。

<select name="department">
    <option value="department_id">department_name</option>
    ...
</select>

但我使用 CodeIgniter form_helper,所以我从我的数据库中获取数据,一个包含行(数组)的数组:

echo form_drop_down('department', $departments_from_DB);

我在 CI 的文档(关于 html_escape() 函数)中读到 form_helper 应该转义其内容:

If you use any of the form helper functions listed on this page, the form values will be automatically escaped, so there is no need to call this function. Use it only if you are creating your own form elements.

但是当我用警报脚本进行测试时,警报有效,所以...

我不知道如何转义部门名称。其实我知道, html_escape() 可以,但是有时需要,有时不需要,有时会转义两次,我有点困惑。

一个解决方案可能是在循环中编写 html 代码,然后转义 PHP 值,但是有没有更优雅的解决方案?

form_dropdown() 函数转义 <option value="xxx">Name</option> 标签的值(在我的示例中为 'xxx'),但不转义标签之间的单词(在我的示例中为 'Name' ).

要转义所有内容,请在给定 form_dropdown() 函数的数组上使用 html_escape()

示例:

$array_data = array(
    'a' => 'Jack',
    '<script>bad_script</script>' => 'John',
    'c' => '<script>another_bad_script</script>'
);

// this will escape the array's key values (Jack and John are ok but not the last one)
echo form_dropdown('select_value', $array_data);

// this will escape the entire array
echo form_dropdown('select_value', html_escape($array_data));