Reputation: 38422
Which of the two is a better way to prevent an xss attack?
I find the first one better because you may forget to add this while displaying.
Upvotes: 3
Views: 933
Reputation: 288260
Reasons for encoding in the display code (i.e. after reading text from the database):
I can't think of any reason for encoding when writing. You mention one may forget to encode data in the displaying logic, but I'd argue you're equally likely to forget it in the database storing code.
Upvotes: 1
Reputation: 61793
The best way(option number 3..) if you ask me is using the latest filter extension to handle filtering for you(PHP5). I like to put filter_input_array at the top of my php file to protect myself against for example POST XSS attacks
$_POST = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
You should read the filter documentation(tutorials) and protect yourself against XSS for input.
Upvotes: 1
Reputation: 45589
A better way would be strip_tags()
and htmlentities()
before saving to db (if you don't mind some extra bits of data).
However, make sure you have taken other precautions as well to protect against SQL injection, by using mysql_real_escape_string()
or a prepared statement data-access abstraction layer, such as PDO.
Upvotes: -1
Reputation: 944320
which of the two is a better way to prevent xss attack.
- HTMLEntities while saving in db
- HTMLEntities while displaying/echoing
2 — you should convert to the target format at the last possible moment. This saves you from problems down the road should you, for example, decide you want to use the same content in an email, a PDF, as text back to the user for editing, etc, etc.
i find the first one better coz you may forget to add this while displaying
You might forget when inserting into the database too.
Also, not all data goes into the database. e.g. A preview of data about to be inserted or data put back into a form because of errors are both possible XSS vectors. You don't want to be dealing with things like "Encode before putting into the database, or when echoing back into the document if it didn't come from a database". Exceptions are the best way to get yourself into a situation where you forget to encode.
Upvotes: 6