【问题标题】:CakePHP: How can i stop inserting/adding html tag during commenting of a post?CakePHP:如何在评论帖子时停止插入/添加 html 标签?
【发布时间】:2011-11-29 06:55:20
【问题描述】:

这是评论表格:

echo $this->Form->create('Comment',array('url'=>array('controller' => 'comments', 'action' =>'add', $listposts['Post']['id']) ) );

echo $this->Form->input('post_id',array('type'=>'hidden','style'=>'width:30%','value'=>$listposts['Post']['id']));  
echo $this->Form->input('name',array('style'=>'width:30%'));
echo $this->Form->input('email',array('style'=>'width:30%'));   
echo $this->Form->input('body',array('rows'=>'5'));

echo $this->Form->end('Comment');

comment.php 模型 =>

var $useTable='comments';
var $belongsTo = array('Post');


var $validate = array(
    'name' => array(
        'required' => true,
        'rule' => 'notEmpty',
        'allowEmpty' => false,
        'message' => 'Enter Name.'
    ),
    'email' => array(
        'required' => true,
        'rule' => 'notEmpty',
        'allowEmpty' => false,
        'message' => 'Enter Email.'
    ),
    'body' => array(
        'required' => true,
        'rule' => 'notEmpty',
        'allowEmpty' => false,
        'message' => 'Enter Body.'
    )
);

}

但在评论过程中,有人可以像这样在评论表单的任何文本框中输入 =>

<script>
    alert("Hello world");
</script>

然后在页面加载期间将显示此警报。 我怎样才能停止在数据库中插入这个 html 标签? 我如何检查这个 html 块?

【问题讨论】:

    标签: php javascript jquery cakephp cakephp-1.3


    【解决方案1】:

    有两种方法可以处理这个问题:清理转义字符串。消毒意味着您删除所有不需要的内容。转义意味着您“禁用”字符串中的任何特殊字符。您应该始终在输出用户提供的内容时对其进行转义:

    echo htmlspecialchars($comment['body']);
    

    您可以选择可能对字符串进行清理,但这可能会很棘手。查看Cake's Sanitize classThe Great Escapism 也很合适。

    【讨论】:

    • 我应该在保存表单字段中的数据之前删除标签吗?或者我应该在回显字符串之前使用 strip_tags() 吗?
    • @guru 取决于。我更喜欢以原始形式存储任何输入并仅在输出期间对其进行更改。如果您立即丢弃信息,您将永远无法取回原件。不过,这真的取决于您和您的优先事项。
    【解决方案2】:

    您可以使用:strip_tags()htmlspecialchars()

    $str = "<script>alert('Hello world');</script>";
    
    echo "strip_tags = " . strip_tags($str);
    echo "htmlspecialchars = " . htmlspecialchars($str);
    

    Demo

    【讨论】:

    • 我应该在保存表单域中的数据之前删除标签吗?或者我应该在回显字符串之前使用 strip_tags() 吗?
    【解决方案3】:
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 2014-07-06
    相关资源
    最近更新 更多