2

Is there a shortcut method to assigning $_GET['values'] to variables?

I currently do like others do:

if(isset($_GET['type'],$_GET['case'])
   $type = $_GET['type'];
   $case = $_GET['case'];

Is there a cleaner method to do this instead of doing like below separately.

 $type = $_GET['type'];
 $case = $_GET['case'];
Norman
  • 6,159
  • 23
  • 88
  • 141

8 Answers8

4

The only one-line code I can think of, to make sure that you still do the necessary checks, is

$type = (isset($_GET['type'])) ? $_GET['type'] : 'a default value or false';

Reading comments, I understand you may want to do this:

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

I would suggest though, to always initialize the variables you need only. The above code will result in getting unknown variables, which may actually give the user a way to manipulate your script.
Example:

index.php?ExpectedVar=1&UserDefinedVar=2

will generate the following variables in your code:

$ExpectedVar // 1 <- you wanted this one
$UserDefinedVar // 2 <- but what about this?

What if you had this script called by some other script?
Then even if you have this code at the top of your file, you may have some variables overwritten from a user defined $_GET!

Disaster case Scenario:
script1.php

<?php 
  $tableToDelete = "old_products";
  include("script2.php");
?>

script2.php

<?php
  foreach($_GET as $key=>$value) {
    $$key = $value;
  }
  // user added &tableToDelete=users
  // DROP TABLE $table
  // will gloriously delete users
?>

Instead by writing a few lines with the original code I posted, you can get the variables you need at the start of your php script and use them with a clear mind.

mavrosxristoforos
  • 3,573
  • 2
  • 25
  • 40
  • the OP has `$_GET['type'],$_GET['case']` as an example, your approach only deals with one GET type i.e `$_GET['type']` only – samayo Sep 26 '13 at 09:21
4

http://docs.php.net/extract

I think you're looking for extract function.

extract($_GET); //now, all of the functions are in current symbol table

JimiDini
  • 2,039
  • 12
  • 19
  • [Be warned ...](http://stackoverflow.com/questions/829407/what-is-so-wrong-with-extract) – HamZa Sep 26 '13 at 09:17
  • 1
    @HamZa absolutely. that's why I would avoid doing something like this, anyway. but the question was about clean way of moving variables from `_GET` to vairables and extract does just that. nothing is cleaner than one function call. Secure-wise, I would suggest to use functions from http://docs.php.net/filter instead – JimiDini Sep 26 '13 at 09:20
4

Well, with array map you can you get the case not just once, but all at once, and you can also check for isset() and empty() at the same time too.

Suppose, you have this URL: read.php?id=1&name=foo&job=student&country=Brazil

Your problem is fetching the $_GET type, and you may need to check if is it empty/isset or not right?

Well, first you create a function to iterate through it.

function checkGet($val){
    return (isset($val) && !empty($val)) ? $val : null;

}

Then, you callback that function with array_map()

$check = array_map('checkGet', $_GET);

And that is it!

If you were to do var_dump($check); now, you would get get all the types, and values:

array (size=4)
  'id' => string '1' (length=1)
  'name' => string 'foo' (length=3)
  'job' => string 'student' (length=7)
  'country' => string 'Brazil' (length=6)

Meaning, after this, instad of doing:

if(isset($_GET['something']) && !empty($_GET['something']))
$var = $_GET['something'];
echo $var; 

Just do:

echo $check['something']
samayo
  • 16,163
  • 12
  • 91
  • 106
1

Try like

foreach($_GET as $key=>$value) {
     $get_arr[$key] = $_GET[$key];
}
print_r($get_arr);
GautamD31
  • 28,552
  • 10
  • 64
  • 85
0

I would do it that way, this way you make sure that it will only return TRUE or FALSE

if (!isset($_GET['type']) || empty($_GET['type'])) {

// Display error

} else {    

$type = $_GET['type'];
$case = $_GET['case'];  

}

Or you can do it that way as well

$type = (isset($_GET['type'])===false)?'':trim($_GET['type']);
$case = (isset($_GET['case'])===false)?'':trim($_GET['case']);
user974435
  • 377
  • 2
  • 13
  • 31
0

$_GET is table, so you can easy use foreach function

For example

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

If you would like to create variables with $key names use variable variables PHP Manual Variable Variables

Choinek
  • 313
  • 2
  • 13
0

You can do it through extract()

extract($_GET, EXTR_PREFIX_ALL, 'g');

so that

$_GET['val'] becomes $g_val

Note the third parameter: g it prepends g_ to the keys.

Pupil
  • 23,834
  • 6
  • 44
  • 66
0

This (untested) class should help you:

class MyGet {
    public static $myValues = array();

    public static function setMyValues($keywords, $where) {
        MyGet::$myValues = array();
        for ($index = 0; $index < count($keywords); $index++) {
            if ((!(isset($where[$keywords[$index]]))) || (empty($where[$keywords[$index]]))) {
                MyGet::$myValues = array();
                return false;
            }
            MyGet::$myValues[$keywords[$index]] = $where[$keywords[$index]];
        }
    }
}

You can use it like this:

if (MyGet::setMyValues(array(0 => "type", 1 => "case"), $_GET)) {
    //the values are initialized
} else {
    //the values are not initialized
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175