I’m using jQuery to check to see if a username is taken. My issue is that $.post seems to escape anything. For example, I use this:
$.post("http://mywebsite.com/check_username.php", {
"username": $("#username_txt").val()
}, function(data, textstatus, xmlhttp){
// do stuff
});
to send the username to the page check_username.php, which is roughly,
$username = mysql_real_escape_string($_POST["username"]);
echo $username; // show the perceived username
echo mysql_query("SELECT * FROM users WHERE username=\"".$username."\";") === false ? 1 : 0;
If the username in the input field is "bob" (with the quotation marks), the return from the data will be \\\"bob\\\"0. Without the mysql_real_escape_string, it reads \"bob\". If I dare to leave it like that, then potential attackers could easily inject SQL code into my application.
I haven’t seen anything on the jQuery documentation on get and post about this, so I’m not sure how to stop this. Barring not using jQuery for my ajax, how do I fix this?
You’ll have to strip out the magic quotes that PHP automatically adds to $_GET, $_POST, and $_COOKIE data. That deprecated feature can be disabled if all your PHP code properly escapes strings before inserting them into HTML, SQL, command lines, etc.