imns
imns

Reputation: 5082

Sanitize search query with php

When a user searches on my site, I grab the get request and do a mysql query against it. My original code looked something like this: $q = $_GET['q'];.

Right now urldecode is adding slashes for me, but I decided to aslo try filter_var with the santize string filter.

Here is my sql when I use $q = urldecode($_GET['q']);:

SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC 

and here is my sql when I use: q = filter_var(urldecode($_GET['q']), FILTER_SANITIZE_STRING);

SELECT * FROM item WHERE title LIKE '%you\'re%' OR description LIKE '%you\'re%' ORDER BY date DESC 

The sql is exactly the same, but I get different results and I'm not sure why? Just using urldecode returns the correct results from the database, but filter_var returns nothing (even though the sql is the same).

I guess my question is, is what's the best way to sanitize and search query string?

Upvotes: 3

Views: 9086

Answers (4)

LifeInstructor
LifeInstructor

Reputation: 1610

The best variant is to use php Sanitize filters http://php.net/manual/en/filter.filters.sanitize.php,

Upvotes: 0

Kerry Jones
Kerry Jones

Reputation: 21838

I would do:

$q = mysql_real_escape_string( stripslashes( $_GET['q'] ) );

Upvotes: 0

thelem
thelem

Reputation: 2773

Urldecode is the wrong function to use - PHP will automatically decode any variables in $_GET so you don't need to, and the PHP Manual says doing so is dangerous.

Often people talk about sanitizing input, but I prefer to think about sanitizing output.

For example, sanitizing input would be:

$q = urldecode($_GET['q']);
$sql = "SELECT * FROM item WHERE title LIKE '%{$q}%'"

// later
echo "These items match '$q'";

And sanitizing output:

$sql = "SELECT * FROM item WHERE title LIKE '%".mysql_real_escape_string($_GET['q'])."%'"

// later
echo "These items match '".htmlspecialchars($_GET['q']).'";

Notice how in the latter example I've used different functions - one for converting the data into a mysql safe format, the other for converting the data into an HTML safe format. You can't know which function you want to run until you know what you're doing with the data.

Others have mentioned parameterised queries. Yes, these are about as secure as you can get and avoid accidental errors, but are not easy to switch to overnight.

Upvotes: 4

Andy Lester
Andy Lester

Reputation: 93646

Don't try to sanitize your data.

Use parametrized queries.

See http://bobby-tables.com/php.html for examples.

Upvotes: 3

Related Questions