views:

39

answers:

1

The example web page has 2 fields and allows a user to enter a title and code. Both fields would later be embed and displayed in an HTML page for viewing and/or editing but not execution. In other words, any PHP or javascript or similar should not run but be displayed for editing and copying.

In this case, what is the best way to escape these fields before database insertion and after (for HTML display)

A: 

You need to use the function htmlspecialchars() in php

that will change any special characters (eg < and >) into their special HTML encoded characters (eg &lt and &gt). When you get these from the database and output them as HTML they will display as code, but won't harm your script or execute.

Thomas Clayson
So, you recommend escaping everything before database insertion and then just displaying it to HTML?
Andres
@Andres: his suggestion of encoding special characters is not the same as escaping. BTW, I don't recommend encoding as this puts you in a situation where you can potentially double-encode. There is no reason you can't insert the data without encoding. You can always filter and/or encode on the way out.
wilmoore
@wilmoore thanks. I also considered encoding on the way out but quickly realized the potential problems that can occur if a programmer forgets to encode before displaying the data. At the moment, I'm using php like mysql_real_escape_string(htmlspecialchars( $data )) where $data is the code, before inserting to the database.
Andres
@Andres: Generally, one would allow the model to handle the encoding on the way out ($model->getTitle()). The "getTitle" method would by default encode, or you can pass "false" to get it back un-encoded. This way, you are guaranteed to have an encoded result (or not if you choose in a particular context). This also protects you from double-encoding.
wilmoore