$_GET & $_POST Question

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
WorldCom
Forum Commoner
Posts: 45
Joined: Sat Jun 24, 2006 8:14 am
Location: Ontario, Canada

$_GET & $_POST Question

Post by WorldCom »

Ok, I have a page that gets called from a <FORM> and also a link <A HREF='page.php?var=$var'>.

So for the variables I need $_GET ... and $_POST for the form.

Is it correct to put something like this:

Code: Select all

$var = $_GET['var'];
$var = $_POST['var'];
so it picks up the variable with either type of input, or should I use some kind of if statement to filter it first?
Note that I do filter the input to make sure nothing nasty comes through.
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Code: Select all

if(!empty($_POST))
    $var = $_POST['var']; 
else
    $var = $_GET['var'];
WorldCom
Forum Commoner
Posts: 45
Joined: Sat Jun 24, 2006 8:14 am
Location: Ontario, Canada

Post by WorldCom »

So simple ..... thanks :)
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post by Jenk »

It would be best to specify the indice required explicitly, and optional default value:

Code: Select all

if (!empty($_POST['var'])) {
    $var = $_POST['var'];
} elseif (!empty($_GET['var'])) {
    $var = $_GET['var'];
} else {
    $var = 'default';
}
If a different value was available in $_POST/$_GET you would get a 'false' positive :)
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'd make that a function. Image
Post Reply