Quick question about input/output security

Soldato
Joined
2 May 2004
Posts
19,950
I've set myself a little project of creating a secure, efficient forum using PHP - I don't plan to release it or anything, it's more to keep what I know about PHP fresh in my head as well as learn more :)

However I have forgotten a little as I haven't coded in a while :p

Am I right in saying I should be using mysql_real_escape_string (I'll be using robmiller's quote_smart function for this) for data going into the database?

So for example when a user is entering something into a form I'd process his/her entry through htmlentities() - e.g. htmlentities($_POST['data'], ENT_QUOTES); along with quote_smart() in the query?

Then for reading from the database I'd just use quote_smart() in the query?

Thanks,
Craig.
 
I'd just use mysql_real_escape_string() on the insert and then htmlentities() when you select it and output it. No real benefit to storing it with entity encoding - in fact it puts you at a disadvantage in a case where you might not want to output the content to a browser, but instead to another medium where character entities will cause problems.

You also don't need to escape the data again, with quote_smart(), when retrieving it from the db as you've already done it once and you're not protecting against anything when you're outputting it.

Just sanitise the data against database injection (mysql_real_escape_string()), and then deal with it on the output. However it does depend on the context really - for performance you might want to do all the sanitising and tag stripping at the insert rather than the select (insert only happens once).
 
Thanks :)

What about when I'm selecting information from a database based on the URL, for example:

PHP:
<?php
$id = $_GET['id'];

$sql = "SELECT * FROM table WHERE id = '$id'";
?>

Am I right in saying the safe way of doing the above would be:


PHP:
<?php
$id = $_GET['id'];

$sql = sprintf("SELECT * FROM table WHERE id = %s", quote_smart($id));
?>

Along with checking that the $id is valid of course (intval() etc.)

Thanks,
Craig.
 
Back
Top Bottom