Friday, June 27, 2008

A useful shortcut in PHP 5

Recently I started using a shortcut for my $_GET variables in PHP 5. It seems that instead of doing the following:

    $page = $_GET['page'];
    $article = $_GET['article'];

There is an easier way where all the $_GET variables can be assigned automatically.

The function is called parse_str(). See the example below:

    //example url is:
    //this would give the following:
    //$page = "home"
    //$article = "934"

So this function uses the ampersand sign (&) to divide the string and assign the elements to variables. I wonder if it works with the validation rules of W3C, because normal & are not allowed in a URL query string. One must use &amp; instead.

UPDATE: It does work with the &amp; hardcoded in a URL. The URL shows a normal & sign, so PHP just parses it like a normal symbol.


Thijs Zumbrink said...

Isn't this unsafe? Reminds me a lot of "register globals" which becomes deprecated in PHP6 with good reason.

Francis Laclé said...

Ha Thijs, correct me if I'm wrong but aren't these as secure as using standard $_GET variables? The only difference is that here you would get an extra $x variable besides just a $_GET['x']. If I don't have this implemented and I add something like &hack=bla in the URL, then PHP would generate $_GET['hack']=bla. Because I'm not doing anything with $hack or $_GET['hack'] in my own code nothing would happen to it. The only risk is when the value of 'hack' would get injected with another value, which isn't really a risk because sensitive data are either stored in POST or SESSION vars.