Forum Moderators: coopster
I am just wondering if I am doing this right. I have a form for user registration (username, password, etc.) and then I do a data check on the user input values to be inserted into the database. This is what I do:
$username=mysql_real_escape_string(htmlspecialchars(strip_tags(($_POST['username']))));
insert into DB
Now, if user types as username: jack'sCar, an echo after data check shows as jack\'sCar, BUT in the database, it shows as jack'sCar? Isn't it supposed to show as jack\'sCar in the DB also? Is the user input data pretty safe after using the above method? Thanks.
Best thing is to encode the data on the fly as you're outputing it to various targets, e.g. to insert into DB:
$qh = mysql_query("insert into DB values('". mysql_real_escape_string($_POST['username']) . "')");
To output to HTML:
echo "You're logged in as: " . htmlentities($username);
URL:
echo '<a href="' . htmlentities('/edituser?name=' . urlencode($username)) . '">';
Also about strip_tags... if you pass all data through htmlentities (as i mention above) it's not absolutely necessary to call strip_tags. But if the data is from user input, and you want to disallow certain characters or strings of characters, it's more user-friendly to tell the user and give them a chance to correct the problem instead of quietly stripping the unwanted chars.
Finally, it's good practice to check for length of string. If the username field in the DB is varchar(20), make sure $_POST['username'] is not longer than 20 (check the length before you pass it through mysql_real_escape_string).
Oh and test, test, test, then test again. :) Write some raw HTML pages or PHP curl scripts that call your real PHP scripts with every value possible: something with a single-quote, something with a double-quote, with a space (may cause trouble in numeric fields), with a new-line, with an html tag, a super long value etc.