Page 1 of 1

isset() driving me crazy

Posted: Thu Sep 30, 2010 7:47 am
by seadog
I have a very simple script using isset() and the logic just does not work using PHP 5.3.1 and 5.2.9 on my localhost and website respectively.
Whatever I do, isset() always seems to return true.
I am new to PHP programming but otherwise not a beginning programmer but I presume I must be making a beginners mistake though am following an example from a book on PHP.
Can anyone help?
The html code and php script are:

<form action="form.php" method="post">
<fieldset><legend>Enter Name:</legend>
<p><b>Name:</b>
<input type="text" name="name" size="20" maxlength="40" /></p>
</fieldset>
<input type="submit" name="submit" value="Submit" />
</form>


// file form.php
<?php
$name = NULL;
$name = $_REQUEST['name'];

if (isset($name))
{
echo '<p>isset was true for $name</p>';
}
else
{
echo '<p>isset was false for $name</p>';
}
?>

Re: isset() driving me crazy

Posted: Thu Sep 30, 2010 8:23 am
by Ketrel
two things to try

1. instead of setting to null
try
unset($name);

2. if that still doesn't work
try instead of isset
if ($name != "")

Re: isset() driving me crazy

Posted: Thu Sep 30, 2010 8:29 am
by DigitalMind
replace $_REQUEST with $_POST

Re: isset() driving me crazy

Posted: Thu Sep 30, 2010 9:59 am
by AbraCadaver
If you submit that form then $_POST['name'] will always be set, so if you do $name = $_POST['name'] then $name is set. If you set $name = NULL then $name is set. Are you trying to see if it is empty? If so use !empty($name).

Re: isset() driving me crazy

Posted: Thu Sep 30, 2010 10:02 am
by John Cartwright
If you are setting the variable just prior to checking whether or not it's set, of course it's going to return true.

The behavior your looking for is in empty()

Re: isset() driving me crazy

Posted: Thu Sep 30, 2010 10:18 am
by DigitalMind
BTW I would use isset($_POST['name']) instead of isset($name) in this case

Re: isset() driving me crazy

Posted: Fri Oct 01, 2010 1:25 pm
by seadog
Thanks for all the replies.
I decided to use strlen() in the end since I am familiar with C and it seems that PHP uses similar methods from what I have seen so far.

Re: isset() driving me crazy

Posted: Fri Oct 01, 2010 1:59 pm
by AbraCadaver
seadog wrote:Thanks for all the replies.
I decided to use strlen() in the end since I am familiar with C and it seems that PHP uses similar methods from what I have seen so far.
Then I guess you don't care if someone just puts a bunch of spaces in the field? If you do care then you'd have to trim() it first, might as well just use empty() :)