0

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 ?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Should i remove tags before saving data from form fields ? Or should i use strip_tags() before echoing strings ?
@guru Depends. I prefer to store any input in its original form and alter it during output only. You will never get the original back if you discard information immediately. It's really up to you and your priorities though.
1

You can use: strip_tags() or htmlspecialchars()

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

Demo

1 Comment

Should i remove tags before saving data from form fields ? Or should i use strip_tags() before echoing strings ?
0

Use this:

http://php.net/manual/en/function.htmlspecialchars.php

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.