[Wolves] PHP global variables

David Goodwin dg at clocksoft.com
Tue Sep 6 19:55:03 BST 2005


> 
> if(!empty($_GET["stupid_variable"]))
>         $stupid_variable = $_GET["stupid_variable"];
> else
>         $stupid_variable = "";		// value to use if empty/missing
> 
> 
> Depending on the type of application and risk level involved you would follow 
> this with further checks on the data type and value to confirm that it is 
> acceptable.

I think a nicer approach would be to do something like :



(In common include file... )
function populate_get_variables($get_variables) {
    foreach($get_variables as $key) {
        if(array_key_exists($key, $_GET) && $_GET[$key] != "") {
            $temp = $_GET[$key];
            if(preg_match("[^A-Za-z0-9\.]", $temp)) {
                debug("Invalid character in $key field.");
                exit(1);
            }
            global $$key;
            # did i say I'm paranoid?
            $$key = htmlspecialchars($temp);
        }
        else {
            echo "Illegal usage : $key not defined correctly.\n";
            exit(1);
        }
    }
}

(At the top of each php script)
require_once("the_common_include_file.php");

$get_variables = array("name", "password", "email_address");
populate_get_variables($get_variables);
# $name now accessible thanks to the above function; and it's safe (to
# display back on teh page, or store in a db)

Obviously the above is quite simple, and relatively inflexible. An
additional (or better) approach would perhaps be to check the size of 
$_GET. (i.e. is it the same size as $get_variables, if not issue error
and abort).

(The above probably depends alot on having one script per particular
task, which some people don't seem to do, instead they have many if/else
statements to determine what's going on (e.g. see PHPBB code)

Have fun,

David.

-- 
David Goodwin
w: http://www.clocksoft.co.uk 
e: david.goodwin at clocksoft.com
t: 0121 313 3850



More information about the Wolves mailing list