views:

23

answers:

3

If I use http://site.com/index.php?page=45 everything looks ok (wanted page loads).

But when I go through http://site.com/index.php?page=45' or http://site.com/index.php?page=45" (quotes are added after digits) page prints an error:

Unhandled Exception (Debug)
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\'
 ORDER BY datePub DESC
 LIMIT 10' at line 9
SELECT *, date_format(date, '%d') AS day, date_format(date, '%m') AS month, date_format(date, '%Y') AS year FRO...
// and paths to my scripts

Thats like a pizza to beer for hacker.

How to filter unwanted symbols (like quotes), so the page won't show my db query (my own error text maybe)?

I have switched off error reporting, but its not a solution (can't use it everywhere).

+1  A: 
$page = (int) $_GET['page'];

or

$page = preg_replace('~[^0-9]~','',$_GET['page']);
Crayon Violent
what do you mean it doesn't help? show your code, how you are using it...casting as an int will force it to be evaluated as an int, chopping off anything after the numbers. preg_replace will remove anything not numbers. If neither of these help, then there is more to your problem.
Crayon Violent
(int) type casts your variable as an integer. lookup type casting
Crayon Violent
>after the numbers thats good, but what about middle or beginning of the number? it can be used there.
Happy
okay well then go for the preg_replace option. But at that point in time obviously someone is trying to hack you, so do you want to try and resolve it to some page they obviously aren't trying to get to, kick them at page 1, or do something about them trying to hack you?
Crayon Violent
I want to redirect all the hackers to some gay site :)
Happy
A: 

Type cast the page variable:

Possible Solution 1:

$page = (int) $_GET['page'];

Test Case:

$str = '45"';
echo (int) $str;

Result:

45

Possible Solution 2:

Or you can reject such invalid value using is_numeric or ctype_digit functions:

if (!ctype_digit($_GET['page'])){
   die('Invalid page value !!');
}
else{
 // continue with the query...
}

Possible Solution 3:

You may use this regex to remove unwanted characters:

$page = preg_replace("/[^0-9]+/", "", $_GET['page']);

Update:

For the text, you should use mysql_real_escape_string function.

Sarfraz
what if the quote is used in the middle of number, or at the beginning?
Happy
quote can also be used on some text-like variables, like ?type=news'. How to filter in that way?
Happy
@WorkingHard: In that case, you should consider other methods like I have shown.
Sarfraz
true for numbers, what about text-like? :)
Happy
@WorkingHard: For the text, use `mysql_real_escape_string` function.
Sarfraz
A: 

Use (int)$_GET['page']. If that doesn't work, you are grabbing the url which means you need to use regular expressions. I don't see why you would want to grab the URL, so you should be ok.