I've made a simple search-script in PHP that searches a mySQL database and outputs the result. How this works is like this:
- User searches for "jack's" through a search-form.
- My PHP-script
GET
s this search, and sanitizes it. - Then the script, with the use of
SELECT
andLIKE
, gets the results. - The script then outputs the result to the user.
- Lastly, the script tells the user that "jack's returned x results." with the help of escaping.
What I would like to ask is, am I doing it right?
This is how I sanitize before SELECTING
from the database:
if(isset($_GET['q'])){
if(strlen(trim($_GET['q'])) >= 2){
$q = trim(mysql_real_escape_string(addcslashes($_GET['q'], '%_')));
$sql = "SELECT name, age, address FROM book WHERE name LIKE '%".$q."%'";
}
}
And this is how I escape before outputting "jack's returned x results.":
echo htmlspecialchars(stripslashes($q)) . " returned x results.";
Is this the correct way to do it?
By the way, I know that PDO and mySQLi is preferred as they sanitize themselves through the use of prepared statements, but I have no real experience with them whatsoever. But I would gladly take a look, if you guys could link me some newbie tutorials/explanations.
Furthermore, I heard that magic_quotes
and charset
could in some way or another lead to injections -- is this correct?
For some reason we need also escape a backslash too.
So, the proper code would be, I believe
For the output, use
stripslashes not needed here.
magic quotes won't harm your security if you won't use them.
charset is dangerous in case of some extremely rare encodings but only if improperly set. if
mysql(i)_set_charset
or DSN (in case of PDO) were used for the purpose - you are safe again.As for PDO, a tag wiki should be enough for starter, I believe