Page 1 of 1

preg_match troubles

Posted: Tue Jun 10, 2003 9:55 pm
by WizyWyg
I have a page that is drawing information from 1 table via an Id#.
I want to prevent someone from "guessing" a number for the id and inputting into the url.


example:

test.php?id=2 is valid (so it takes give you the correct information)

but i want to prevent someone from typing:

test.php?id=200 which is not valid, since the id doesn't exist in the DB (hence causing the script to not display correctly)

Currently I have this on test.php:

Code: Select all

if (! ((preg_match("/^\d+$/",get_param("id"))) and get_db_value("SELECT id FROM table WHERE id=".get_param("id"))))
{
header("Location: testpage.php");
exit;
}
Which does the above as the way I want it to....
and here's the "but".

I have a total of 6 records ( this will not change )

For this page though, I only want records 4-6 to be only accessible, and still return them to testpage.php if they try to input id=1 or id=200. So the only "valid" id's for test.php to give information for is id=4, id=5 and id=6

What should I change?

Posted: Tue Jun 10, 2003 10:13 pm
by ayron
apply something like this

if ($id < 4)
$id = 4;
if ($id >6)
$id = 6;

before grabbing the data

Posted: Tue Jun 10, 2003 10:16 pm
by SteveW
I'm pretty new to development in general so I could be way off base here, but couldn't you just so something like:

Code: Select all

if( $$_GET&#1111;'id'] < 4 | $_GET&#1111;'id'] > 5 )  &#1111;code]
that would eliminate both problems at once (obviously not very portable though)

Posted: Wed Jun 11, 2003 12:08 am
by m3rajk
if you don't want someoen to be able to guess, but want to pass, if it's at all possible, call the page with post, that way the variable is never seen, you don't have to let them know it's page.php?id=#

Posted: Wed Jun 11, 2003 12:23 am
by nielsene
There are lots of good solutions presented above, but if you want to stick with a regexp (not sure why you would for this case) you can use

Code: Select all

... preg_match('/^[4-6]$/', get_param("id")) ...
to only match a single digit chosen from the inclusive range 4-6.

Posted: Wed Jun 11, 2003 2:26 pm
by WizyWyg
This also worked:

Code: Select all

$id = get_param("id");
if (! ((preg_match("/^d+$/",get_param("id"))) and get_db_value("SELECT id FROM table WHERE id=".get_param("id"))))
{
header("Location: testpage.php");
exit;
}
elseif($id < 4)
        {
header("Location: testpage.php");
exit;
}