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.
Have you tried the processData
property for $.ajax
?
http://api.jquery.com/jQuery.ajax/
Composing SQL directly with user-generated text is suicidal. See here if you don't understand why.
Composing SQL with mysql_real_escape_string applied to user-generated text is a poor idea, as it makes the queries difficult to optimize (although compared to not using mysql_real_escape_string at all it's like jabbing yourself in the neck with a sharp pencil compared to jabbing yourself in the neck with a running chainsaw)
Maybe maghic_quotes_gpc config parameter is set to on in the PHP.ini file.
If you have access to that file change the value to off.
If you don't have access then use get_magic_quotes_gpc function to see if magic_quotes is "on" if it is not then call the mysql_real_escape_string function else bypass it.