Jump to content

securing $_GET variables


Reaper0167

Recommended Posts

I found this little snippet online. Is this a safe way to keep others from messing with my url variables?

 

<?php
$allow = array('pageid', 'sectionid', 'articleid');

foreach($_GET as $key => $value)
{
    $valid = false;
    foreach($allow as $key_allow => $value_allow)
    { 
        if($key==$value_allow)
        {
            $valid = true;
        }
    }

    if($valid==false)
    {
        header('location:errorpage.php');
        exit();
    }
}
?>

Link to comment
https://forums.phpfreaks.com/topic/163575-securing-_get-variables/
Share on other sites

That's fine, yes. It's called a whitelist.  But, you can just make use of in_array to make that more efficient and less long-winded.

 

For one thing, not really sure why you are looping through the $_GET array, as you probably are only passing and using just one, to signify some page id, right? So just refer to it explicitly instead of using a whole foreach loop.  Then you can get rid of the nested foreach loop with that in_array so overall you'd just have this:

 

$allow = array('pageid', 'sectionid', 'articleid');

if (!in_array($_GET['variable'],$allow)) {
  header('location:errorpage.php');
  exit();
}

 

It's in essence the same principle of whitelisting, just written more efficiently.

So by doing something along these lines, I really shouldn't worry too much about hackers coming in to change things up with the GET vars?  I'm not into the PHP hacking stuff, but couldn't someone still change something, or if they were up to something, would there attack script still see that the only variable that were allowed were the ones in the array?

someone can change your GET vars to whatever they want but if the value is not in the whitelist, it's invalid, and that's all there is to it. But it obviously depends on what kind of values you are expecting as to the effectiveness of a whitelist.  It is not really efficient or even possible to make an array of "allowed" values if for instance the value can be a number.  So you have to just validate it, like anything else.  So in other words, a whitelist is a very effective way to validate some values/situations, but it's just one thing, and it really depends on the situation.

Well, one page grabs the id number of a certain row in the database with $_GET, so that would be a number, and there could be hundreds, maybe thousands of numbers. What would you suggest for a situation like this?  Then the oher would be that I use $_GET to retrieve a url variable. And that url could always be different.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.