简体   繁体   中英

handle invalid URL querystrings

I have abit of an issue and wasnt sure whether this was the place to be to resolve it. Suppose i have a url as follows: http://localhost/products/1010/minprice/1/maxprice/100/

Now lets say someone tries to alter this url by removing part or all of the variable name products, minprice and maxprice. Is there anyway to do a check to make sure the url is valid and if the variables have been altered, can they simply be removed when the page is re-directed?

I currently have this to check the URL, this is just another URL example:

if(preg_match('#^/carsearch(.*/)?(manufacturer/([A-Za-z0-9\-%]+))(/.*)?$#',$uri,$tmatch))
        $return['manufacturer'] = $tmatch[3];

Then to check the query string variables I have:

if($_GET['manufacturer'] != null) {
$n .= 'manufacturer/'.$_GET['manufacturer'].'/';

}

The page is re-loaded with the new $n variable which holds the new valid URL. The URL is build fine but the page just keeps reloading as you can imagine. I was just wondering, is there a better way to do this? I dont even know if i'm on the right track.

Your help would be much appreciated.

if(isset($var))

To check if a variable is isset. You could also do something like

if(isset($var) && product_exists($productID))
   //accept
else
   //deny

It's the same principles no matter what you are doing.

When you pass parameters to a page, they can always be changed by the client (even when passing the data as a form POST or like you are doing in the URL). You should use a validation procedure in order to make sure that the URL is in the format you are expecting. One way of doing this is by using a regular expression, for example:

if ( preg_match( "/^\/products\/\d+\/minprice\/\d+\/maxprice\/\d+\/$/", $url ) != 1 )
{
    echo( "Stop changing my URL!" );
}
else
{
    echo( "Thanks for not changing anything!" );
}

I see that you are using some kind of rewrite method which you didn't specify so what you have to do is get the value of the request path into the variable $url before testing it. The regular expression simply tests for the following:

  1. The start of the string (^)
  2. /products/ (/products/ - forward & backward slashes must be escaped by another backslash because slashes are a part of the regular expression syntax).
  3. A digit, minimum one (\\d+)
  4. /minprice/
  5. Digits
  6. /maxprice/
  7. Digits
  8. /
  9. The end of the string ($) which means nothing else can come after the sequenec.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM