As I was learning from couple of years old tutorials I have end up with following code which IS vulnerable for SQL injections.
Can someone explain to me how to work with mysql_real_escape_string()?
Is this currently bulletproof method?
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$usr = $_SESSION['usr'];
$live = (isset($_POST['live']))?1:0;
$created = date("F j, Y, g:i a",time()+60*60);
$title= clean($_POST['title']);
$content = clean($_POST['content']);
//Create INSERT query
$qry = "INSERT INTO news( usr, live, created, title, content) VALUES( '$usr', '$live', '$created', '$title', '$content') ";
$result = @mysql_query($qry);
Yes, it is. In this case.
Note there is nothing like “universal sanitization”. Let’s call it just quoting, because that’s what its all about.
When quoting, you always quote text for some particular output, like:
likeexpression for mysql queryFor each case, you need different quoting, because each usage is present within different syntax context. This also implies that the quoting shouldn’t be made at the input into PHP, but at the particular output! Which is the reason why features like
magic_quotes_gpcare broken (I recommend to keep it switched off).So, what methods would one use for quoting in these particular cases? (Feel free to correct me, there might be more modern methods, but these are working for me)
mysql_real_escape_string($str)mysql_real_escape_string(addcslashes($str, "%_"))htmlspecialchars($str)json_encode()– only for utf8! I use my function for iso-8859-2mysql_real_escape_string(addcslashes($str, '^.[]$()|*+?{}'))– you cannot use preg_quote in this case because backslash would be escaped two times!preg_quote()