Welcome to WebmasterWorld Guest from 54.147.10.72

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Validating URL parameters before running database queries

     

ocon

11:52 pm on May 15, 2012 (gmt 0)

5+ Year Member Top Contributors Of The Month



I'm using url parameters to search my database with. For security reasons I need to make sure that these parameters are valid and not trying to do things like inject code. I've never been able to come up with a bulletproof and not over-thought way to do this simple task. I think one of the problems is values taken from the parameters are automatically treated as strings. Feedback is greatly appreciated.

/index.php?set=4&lat=34.439395963&lng=-84.5

$set can be 1, 2, 3, 4, or 5.

$lat can be any number between -90 and 90, for example: -90.0000, -87, 0, 45.454545, 89.999999

$lng can be any number between -180 and 180

If any of the values is outside of expected behavior I'd like to kill the script.

rainborick

12:21 am on May 16, 2012 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



For something this straightforward, I'd probably take the brute force approach:

$paramsGood = true;
$reason = '';
if ( (isset($_GET['set'])) && (isset($_GET['lat'])) && (isset($_GET['lng'])) ) {
$set = $_GET['set'];
$lat = $_GET['lat'];
$lng = $_GET['lng'];
if (($set<1) || ($set>5) || ($set != floor($set)) { $paramsGood = false; $reason .= "SET out of bounds.\n"; }
if (($lat<-90) || ($lat>90)) { $paramsGood = false; $reason .= "LAT out of bounds.\n" }
if (($lng<-180) || ($lng>180)) { $paramsGood = false; $reason .= "LNG out of bounds.\n"; }
} else {
$paramsGood = false; $reason = "Parameter missing.";
}
if (!$paramsGood) { die($reason); }

g1smd

3:28 am on May 16, 2012 (gmt 0)

WebmasterWorld Senior Member g1smd is a WebmasterWorld Top Contributor of All Time 10+ Year Member Top Contributors Of The Month



The above approach is good but if you were using "friendly" URLs you could eliminate all "non digit" requests at the URL rewriting stage of the game.

RewriteRule ^s([1-5])-la([0-9.-])+-lo([0-9.-])+$ /index.php?set=$1&lat=$2&lng=$3 [L]

You'd still want to check the limits within your PHP, or other, script as above. Whatever you do, if any parameters are missing or out of bounds you should return 404 for that request.

In PHP you can cast the parameter value as an integer before checking the limits.

rocknbil

3:52 pm on May 16, 2012 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Keep only what you want and throw everything else away. I'd use the following to check that and apply rainboric's idea for range as well:

$lat = -45.6;
$lng = 78.88;
if (is_numeric($lat) and is_numeric($lng)) {
echo "$lat and $lng are numeric";
}
 

Featured Threads

Hot Threads This Week

Hot Threads This Month