Zend - The PHP Company




Security

Add Code


Pre-validating GET/POST vars  

Type: code fragment
Added by: bu22
Entered: 27/06/2003
Last modified: 09/12/2002
Rating: - (fewer than 3 votes)
Views: 7645
This simple security check ensures that a php script does not receive any unexpected rogue GET or POST vars. Just call this simple function at the top of each script to help protect it from malicious attacks.


<?php
function check_received_params($allowedParams_in$arrayToCheck_in)
{
    
// makes sure only the items in the $allowedParams_in
    // are found in the array $arrayToCheck_in
    // returns true if there are no unexpected params in the array
    // returns false otherwise

    
$numAllowed count($allowedParams_in);
    if (
count($arrayToCheck_in) <= $numAllowed) {
        while (list(
$k$v) = each($arrayToCheck_in)) {
            
$found false;
            for(
$i 0$i $numAllowed$i++) {
                if (
$k == $allowedParams_in[$i]) {
                    
$found true;
                    break;
                }
            }
            if (!
$found) {
                return 
false;
            }    
        }
    } else {
        return 
false;
    }
    return 
true;
}
?>


Usage Example


<?php

// ensure we don't have any get parameters sent to
// this script other than $_GET['sid'] and $_GET['a']
if (!check_received_params(array('sid''a'), $_GET))
    die(
'Hack intrusion via URL parameters detected!');

// ensure we don't have any post parameters sent to
// this script other than $_POST['username'] and $_POST['password']
if (!check_received_params(array('username''password'), $_POST))
    die(
'Hack intrusion via POST parameters detected!');


// rest of script ...

?>


Rate This Script





Search



This Category All Categories