Solved

A simple empty() / isset() comparison.

Posted on 2004-10-01
17
497 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
ID: 12205416
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
ID: 12205431
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
ID: 12205662
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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 15

Expert Comment

by:nicholassolutions
ID: 12205738
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
ID: 12208854
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
ID: 12209887
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
ID: 12213250
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
ID: 12214753
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
 
LVL 5

Expert Comment

by:prsupriya
ID: 12219915
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
ID: 12242976
> 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
ID: 12243536
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
ID: 12243547
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
ID: 12244014
<<
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
ID: 12244044
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
ID: 12245469
> 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
ID: 12246300
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
ID: 12246872
note the use of the words "old" and "were" :-)

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

Mike
0

Featured Post

Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

832 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