October 8th, 2012, 12:54 AM
Php & mysql security
I'd like to ask which way is better to protect my scripts from hacking / sql injections ?
is $uid= htmlspecialchars($_POST['uid']);
i use htmlspecialchars for all the $_POST/$_GET types and also make sure that sql parts include $uid and other tags in ''.
Is that secure enough? or its not secure at all or just give me an advice how to improve script security.
Please reply even if its good enough so i would know if i'm doing everything right
October 8th, 2012, 03:56 AM
this is not secure at all, because htmlspecialchars is for escaping HTML characters (just like the name says). What you need to do is escape chracters that have a special meaning in SQL. Those are two completely different things. All your function will do is mess up the strings.
In fact, you should forget the idea of a magic allround escaping function that takes care of everything. This doesn't work. Filtering input depends on the specific context and requires specific precautions. So do not just apply a function to all input. Instead, escape the input specifically for the particular context.
When you use the old mysql_ functions, this would look like this:
Note that it's not always enough to escape special characters. Sometimes you need to do additional things (like the quotes for SQL values). And sometimes all escaping doesn't help (like when you insert user input in a <script> element).
$sql = "
`email` = '" . mysql_real_escape_string($_POST['email']) . "'
The best approach, however, is to completely separate code and data. In SQL, you can do this with prepared statements (as provided by the Mysqli library or the PDO interface).