Pengun
Pengun

Reputation: 744

PHP isset : is this redundant?

When my form has been submitted i always check if the form is isset and then check if all fields are also isset

This is my php code :

if(isset($_POST)) {
  if(isset($_POST['username'], $_POST['password'])) {
    // process
  }
}

My question is, does my first check of isset is if the form itself is submitted and then check again for each input if it isset or if the moment i use

if(isset($_POST)) { }

it will actually check of the fields inside that form?

i hope you get my point thanks in advance.

Upvotes: 0

Views: 171

Answers (3)

Pavel Štěrba
Pavel Štěrba

Reputation: 2912

Well, $_POST is always set, so first statement is not necessary.. Check only if specific fields are set.

EDIT: As noted in comment, isset() give you only information, if some variable is set, not if it has some value. empty() can tell you, if you have something in it.

EDIT 2: Just to be sure if empty() will or will not notice you on undefined POST field, try this:

error_reporting(E_ALL);
var_dump(empty($_POST['undefined']));

You will see that empty() works with undefined indexes too.

Upvotes: 8

Nostalgie
Nostalgie

Reputation: 564

wtf??

BETTER use $_SERVER['REQUEST_METHOD']

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// process
}

Upvotes: -1

hek2mgl
hek2mgl

Reputation: 157990

If you want to check if a post index has been sent, reagardless if it contains an empty string or some data use array_key_exists():

if(array_key_exists($_POST['foo']) && array_key_exists($_POST['bar'])) ..

Upvotes: 1

Related Questions