简体   繁体   中英

CakePHP: How can i stop inserting/adding html tag during commenting of a post?

This is the form for comment:

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');

The comment.php model =>

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.'
    )
);

}

But during commenting someone can type in any textbox of the comment form like this =>

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

Then this alert will be displayed during the page load. How can i stop inserting this html tags in database ? How can i check this html block ?

There are two ways to handle this: sanitizing or escaping the string. Sanitizing means you strip all unwanted content out. Escaping means you "disable" any special characters in the string. You should always escape user-supplied content when outputting it:

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

Optionally you may want to sanitize the string, but that can be tricky. Look into Cake's Sanitize class . The Great Escapism is also apropos.

You can use: strip_tags() or htmlspecialchars()

$str = "<script>alert('Hello world');</script>";

echo "strip_tags = " . strip_tags($str);
echo "htmlspecialchars = " . htmlspecialchars($str);

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM