Easiest and most efficient way to get data from URL using php?

10,999

Your second bit of code is wrong. It ought to be like

foreach ($_GET as $key => $value) {
    $$key = $value;
}

if i understand your intent. However, you're basically reinventing register_globals, which....eh. That'll get ya hacked.

If you have certain variables you want to get, you could do like

foreach (array('Sports', 'cat', 'question') as $key)
{
    $$key = $_GET[$key];
}

which is less likely to overwrite some important variable (whether by accident or because someone was messing around with URLs).

Share:
10,999
Phil
Author by

Phil

Enthusiastic lover of Jesus who enjoys web developing.

Updated on June 04, 2022

Comments

  • Phil
    Phil almost 2 years

    Solution?

    Apparently there isn't a faster way, I'm okay with that.


    I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.

    I am passing in values into a php script. I am using $_GET so the URL looks like this:

    /poll_results.php?Sports=tennis&cat=Sports&question=Pick+your+favorite+sports

    Now I know how to accept those values and place them into variables like so:

    $sports = $_GET['Sports'];
    $cat = $_GET['cat'];
    $question = $_GET['question'];
    

    Super simple yet if I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason. I know there is a better way of doing this. I have tried list($var, $var, $var) = $_GET but that doesn't work with an associative array just indexed ones (i think).

    I also tried variable variables like so:

    foreach($_GET as $value) {
        $$values = $value;
        echo $$values;
    }
    

    But that gave me a Notice: Undefined variable: values in poll_results.php on line 14. Line 14 is the $$values = $value. I don't know if that's a big deal or not... but I'm not turning off error reporting as I am still in the process of building the script. It does do what I want it to do though...

    Any answers will be copied and pasted into my question so the next person knows :D

    Thanks guys!