views:

80

answers:

3

Scenario:

I have a blog that I want to make a post to. I have a form set up where I can write out a blog post and submit it to a seperate php page that then stores it in a database (after it confirms it is me posting) where it will be read from and displayed on the home page. How can I easily escape any quotes or anything that will interfere with it being stored in the database but still allow it to be displayed properly (with all formatting intact)?

Thanks

+4  A: 

The only things that will interfere with it being stored in a MySQL database can be easily escaped by mysql_real_escape_string().

When you pull it out of the database, everything will look the same as before it was escaped and put in. Before you display it on a web page, you'll want to run htmlspecialchars() on the text to prevent any malicious scripting from having an effect.

An optional command would be strip_tags() if you don't want the text to contain any HTML at all.

zombat
+4  A: 

Prepared statements in PHP will do a good job of taking care of sanitizing data as it goes into the database.

shambleh
+1: Bind variables are far, far better than trying to apply escapes.
S.Lott
+1  A: 

Prepared statements are always a really good idea. But, you might consider moving your database code to a stored procedure. This will increase security and performance (in most cases, depending on what database you use and how you cache results).

If you are not going with the stored procedures route, also make sure to disable multiple lines of commands per call to database. This should be in the database config files. It will disable the possibility of doing this:

your command;malicious command

Although there are other ways, this is definitely the most secure.

Alejandro
thanks for the info!
Petey B