coool
coool

Reputation: 8297

php isset do you need it in a form check?

I trying to understand if a isset is required during form processing when i check $_REQUEST["input_name"] if no value is passed it doesn't cry about it and php doesn't throw out an error if you are trying to access a array item which doesn't exist....i can use if($_REQUEST["input_name"]).. what about "empty" even in those cases i can use if()

THnks

Upvotes: 1

Views: 3569

Answers (5)

karim79
karim79

Reputation: 342635

I wouldn't recommend using the $_REQUEST superglobal for capturing form input, unless you're testing a form. Use $_GET or $_POST instead, unless you have a really good reason.

Also, isset() and array_key_exists() both do the same trick with regard to array keys, although array_key_exists() is clearer in an arrays context.

I recommend using:

error_reporting(E_ALL); //E_ALL - All errors and warnings

within your development environment, as that can expose where better practices might be applied, such failure to declare variables before they are used, etc.

Upvotes: 6

Paul Kroll
Paul Kroll

Reputation: 570

Generally, at least for testing, set error reporting to E_ALL (all errors and warnings) either in your php.ini or in code using error_reporting(E_ALL); (Look into adding E_STRICT too.) Better to get an obvious notice about an error up front, than to have something subtle go wrong that you don't catch till later.

Avoid using $_REQUEST, which is too vague (it includes GET, POST AND cookie values), and use the $_POST or $_GET if those are what you really mean, and do check with isset($_POST["input_name"])

The short answer is "Yes." :)

Upvotes: 3

dongo
dongo

Reputation:

using $_REQUEST is pretty much a hack. You should be using $_POST or $_GET (depending on what you are doing) and you should use isset().

Every book I've read on PHP seems to say that.

Upvotes: 4

Paolo Bergantino
Paolo Bergantino

Reputation: 488434

There are different type of error levels. Checking a variable that is not set only throws a notice. Your error reporting is probably set to ignore those. It is best practice to always use isset when you want to check if a variable has been set, although it does have its gotchas.

Doing only what you are doing above, for example, if $_REQUEST["input_name"] is the string "0", it will evaluate to false. Also it is not a good idea to use $_REQUEST to begin with, as it can be affected by stuff like cookies and such and it's usually a code smell for bad architecture.

Upvotes: 5

Ian
Ian

Reputation: 25336

if($_REQUEST["input_name"])

will throw a notice (error) if "input_name" doesn't exist, so isset() is recommended.

Upvotes: 2

Related Questions