Solved

A simple empty() / isset() comparison.

Posted on 2004-10-01
17
486 Views
Last Modified: 2008-02-01
When I am checking to see if the user entered a value for a particular form element what should I use  empty() or isset()

is one more secure than the other or more accurate?


Thanks!

Randy
0
Comment
Question by:rjohnsonjr
  • 5
  • 3
  • 3
  • +5
17 Comments
 
LVL 15

Expert Comment

by:nicholassolutions
Comment Utility
isset() returns true if the variable EXISTS.
empty() returns true if the varaible is EMPTY.

From the PHP manual: empty() returns FALSE if var has a non-empty and non-zero value. In otherwords, "", 0, "0", NULL, FALSE, array(), var $var;, and objects with empty properties, are all considered empty. TRUE is returned if var is empty.

Both empty() and isset() will test if a variable EXISTS, but only empty() will probe the actual VALUE of the variable for 'emptiness' (as defined in the the quote from the manual).

consider the following:

<?php
isset($a);         //FALSE, $a does not exist
empty($a);      //TRUE, $a is does not exist
$a="";
isset($a);         //TRUE, $a exists and is set to ""
empty($a);      //TRUE, $a exists, but is empty
$a=0;
isset($a);         //TRUE, $a exists and is set to 0
empty($a);      //TRUE, $a exists, but is 'empty' because it is zero (see the criteria for 'emptiness' above)

Cheers,
Matt
0
 
LVL 15

Accepted Solution

by:
nicholassolutions earned 500 total points
Comment Utility
So, to answer your question more practially, you probably want to use empty() if you are checking user input ;)
You can get more info about the function (including some helpful user comments) here:
http://us4.php.net/manual/en/function.empty.php
0
 
LVL 10

Expert Comment

by:eeBlueShadow
Comment Utility
There is one exception to that rule: checkboxes

<form>
<input name='one' />
<input name='two' value='2' type='checkbox'>
<input name='three' value='3' type='submit'>
<input name='three' value='III' type='submit'>
</form>

This form will produce
for one - $_GET['one'] is "" if nothing was entered, otherwise equals entered value
for two - $_GET['two'] equals '2' if the checkbox was ticked *BUT ISN'T DEFINED IF THE BOX WASN'T TICKED*
for three - $_GET['three'] equals '3' if the '3' button was clicked, or 'III' if the 'III' button was ticked

so, use empty() for all inputs except checkboxes, and isset() for checkboxes.

Another use for isset is if you have for example form.php submitting a form to form.php - itself. in the code snippet above, if the following code is put in the same page

<?php
  if(isset($_GET['three']))
  {
    // form was submitted, validate
    if(!isset($_GET['two'])) echo "You must click the checkbox!"
  }
?>

it will only be run after the form was submitted
0
 
LVL 15

Expert Comment

by:nicholassolutions
Comment Utility
Actually, empty() also checks if a value is not defined.

eg:

$a=1;
empty($a);         //FALSE
$empty($b);      //TRUE -- $b does not exist

so, it can easily check if a checkbox variable is undefined. empty() is essentially the same as isset(), except that it performs additional checks for emptiness as well.


Cheers,
Matt
0
 
LVL 2

Expert Comment

by:dboeke
Comment Utility
I concur:

<?PHP
$a = " ";
$b = "";
echo "<PRE>";
echo "\n isset a: " . isset($a);
echo "\n isset b: " . isset($b);
echo "\n isset c: " . isset($c);
echo "\n empty a: " . empty($a);
echo "\n empty b: " . empty($b);
echo "\n empty c: " . empty($c);
?>

Result:

 isset a: 1
 isset b: 1
 isset c:
 empty a:
 empty b: 1
 empty c: 1
0
 
LVL 11

Expert Comment

by:neester
Comment Utility
Just a side note...
I ALWAYS use the PHP function -

import_request_variables()

Which will basically import all the form variables...

eg,
you have a form with 3 elements, name, email and age.

then if you do this:

import_request_variables('cgp', 'VAR_');

all those variables will be:

$VAR_name, $VAR_email, $VAR_age

then i check if the var is empty like this:

if (!$VAR_name){$ERROR = "NAME EMPTY!";}
0
 

Expert Comment

by:dewed
Comment Utility
For form validation, you may want to use is_string  instead, or if checking fora number, like someone's age, use is_numeric    this will verify that the variable was populated and that it is the type of data you want.
0
 
LVL 2

Expert Comment

by:Rajkumar_G
Comment Utility
To check whether the user entered data for the form element, the better way is to use empty. isset will also work for this. But for checkboxes and radio buttons the values are not checked correctly.So the better way is to use empty to check whether form element has value or not.
Here is one simple example, to explain u the concept, From this u very well understand which one u should use to solve your needs.

ex.html
-------

<html>
<head>
</head>
<body>
 <form name="form_issrt_check" method="post" action="ex.php">
  <input type="text" name="name">  <br>
  English<INPUT TYPE="CHECKBOX"  name="language1" value="English">
  Tamil<INPUT TYPE="CHECKBOX"  name="language" value="Tamil">
  Telugu<INPUT TYPE="CHECKBOX"  name="language2" value="Telugu"> <br>
  <INPUT TYPE="RADIO"  name="sex" value="Male">Male
  <INPUT TYPE="RADIO"  name="sex" value="Female">Female  <br>
  <input type="submit" name="Submit">
</body>
</html>



ex.php
------

<?

 echo "<br>Name :  ".$_POST['name'];
  echo "<br>Languages  : ".$_POST['language'];
  echo "<br>Languages  : ".$_POST['language1'];
  echo "<br>Languages  : ".$_POST['language2'];
  echo "<br>Sex  : ".$_POST['sex'];

  echo "<br>Isset for Name   :  ".isset($_POST['name']);
  echo "<br>Isset for Language   :  ".isset($_POST['language']);
  echo "<br>Isset for Language1   :  ".isset($_POST['language1']);
  echo "<br>Isset for Language2   :  ".isset($_POST['language2']);
  echo "<br>Isset for Sex   :  ".isset($_POST['sex']);


  echo "<br>Empty for Name   :  ".empty($_POST['name']);
  echo "<br>Empty for Language   :  ".empty($_POST['language']);
  echo "<br>Empty for Language1   :  ".empty($_POST['language1']);
  echo "<br>Empty for Language2   :  ".empty($_POST['language2']);
  echo "<br>Empty for Sex   :  ".empty($_POST['sex']);
?>

Try this simple code to get the problem solved according to  your requirements.
0
Easy Project Management (No User Manual Required)

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 5

Expert Comment

by:prsupriya
Comment Utility
Hi!,

See below

<?php
$var = 0;

// Evaluates to true because $var is empty
if (empty($var)) {
   echo '$var is either 0, empty, or not set at all';
}

// Evaluates as true because $var is set
if (isset($var)) {
   echo '$var is set even though it is empty';
}
?>

Conclusion:
If you want to check whether the variable is set and the value is not null or zero use empty()
If you just want to find out whether the variable is defined or not(irrespective of the value) then use isset()

Hope this helps.
S:

 
0
 
LVL 10

Expert Comment

by:frugle
Comment Utility
> import_request_variables('cgp', 'VAR_');

I thought it should be import_request_variables('gpc', 'VAR_');

Your way makes it easy to forge cookie data by passing it along the querystring.

Mike
0
 
LVL 11

Expert Comment

by:neester
Comment Utility
FRUGLE<
Yeah you can forge cookies - but thats why you use seperate imports if you like.
BTW The order of the g,p,c dont matter.

I usually have:


import_request_variables('gp', 'INVAR_');
import_request_variables('c', 'COOKIE_');

that makes my life easier, and cookies arent forged.
although I code my PHP, so that a cookie can be forged if they like.
the content of the cookie is vital to whatever the process is.
0
 
LVL 11

Expert Comment

by:neester
Comment Utility
Just incase someone doesnt understand why that stops forging.
Your code will expect:

$COOKIE_login

and if they forge it, they will be inputing:

$INVAR_login

:)
0
 
LVL 10

Expert Comment

by:eeBlueShadow
Comment Utility
<<
Just incase someone doesnt understand why that stops forging.
Your code will expect:

$COOKIE_login

and if they forge it, they will be inputing:

$INVAR_login
>>

Excuse me for this question, but if you're going to go to this trouble, why not just use the $_GET, $_POST and $_COOKIE variables - you know where the data you want is coming from after all.

And I'd disagree that the order of the GPC doesn't matter, from the PHP manual (http://php.net/manual/en/function.import-request-variables.php)

>> Note that the order of the letters matters, as when using "gp", the POST variables will overwrite GET variables with the same name.
0
 
LVL 11

Expert Comment

by:neester
Comment Utility
eeBlueShadow.

It makes it a lot easier when you use the variables inside Quotes.
becuase you dont need  {} around them...
and it just becomes a lot simpler really...
Well its your opinion really.

Yeah the order means they are over written - forgot that - although its rarely an issue for me.
I doubt for anyone really, never-the-less thanks for bringing it up.
I had forgotten about that :)
0
 
LVL 10

Expert Comment

by:frugle
Comment Utility
> Yeah the order means they are over written

That was my point entirely :-)

I would much rather use the $_GET, $_POST and $_COOKIE variables than be "lazy" and run a generic import of anything thrown at the script - how many old forums were insecure because you could tag &admin=1 to the end of the url?

Mike
0
 
LVL 11

Expert Comment

by:neester
Comment Utility
Frugle...
Yeah but that is stupid coding, not being lazy...
If someone makes the cookie: admin=1
then anyone could fake the cookie anyway.

your cookie shouldnt store anything of any meaning to anyone, except your server.
Thats one of the biggest rules and if you dont follow that then your website security is seriously lacking...
0
 
LVL 10

Expert Comment

by:frugle
Comment Utility
note the use of the words "old" and "were" :-)

this is drifting OT though - has the question been answered fully?

Mike
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
This article discusses four methods for overlaying images in a container on a web page
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now