0

I am trying to better understand the ISSET() function. It is my understanding that when used properly, I can determine if a "submit" button was pressed or not because the function determines true or false. I have written some html code that uses the HTML Tag and HTML tag type submit. What I was trying to test was whether the ISSET function would return False while the button was not pressed and True when it was pressed.

Using Wordpress Plugin called "Woody snippets" it allows the combination of HTML and PHP in a shortcode.

Please see my code below:

I have been trying to follow a validation video on youtube = https://youtu.be/x_-HdHijmkw

I did everything line for line and initially it worked, upon refreshing the page, it did not clear all of the variables and the isset function acted as if the boolean was true. I thought it was my cache, so I cleared it. Still the ISSET funtion acts as if the boolean is true.

<?php
if (isset($_GET['fname']) && isset($_GET['lname'])) {
$fname = $_GET['fname'];
$lname = $_GET['lname'];
echo "Hello ".$fname;
}
?>

<form action='' method='get'>
First Name: <input type="text" name="fname"><br>
Last Name: <input type="text" name="lname"><br>
<input type="submit" value="Greet Me"><br>
</form>  

I expected upon refresh that the isset() function and the variables used to determine true or false would be false until I entered values and pressed the button again.

ItsEricJS
  • 19
  • 5
  • What was your url when you thought it was supposed to clear, but didn't? –  Feb 02 '19 at 16:21

2 Answers2

0

Pre info: isset($a) && isset($b) is equivalent to isset($a,$b)

isset() proofs the existence of a var, not if it is empty. Try

if ( isset($_GET['fname'],$_GET['lname']) 
    && strlen($_GET['fname']) 
    && strlen($_GET['lname'])  { ...
Wiimm
  • 2,971
  • 1
  • 15
  • 25
0

isset() checks whether the variable exists and will still return true for empty strings, 0, and NULL values. A quick solution would be to use !empty() instead:

if (!empty($_GET['fname']) && !empty($_GET['lname']))

See: In where shall I use isset() and !empty()

tshimkus
  • 1,173
  • 2
  • 17
  • 24
  • `emtpy()` fails, if string is "0". – Wiimm Feb 02 '19 at 16:31
  • Sure, but I don't see how that would be an issue in this use case. If the user enters 0 it will print "Hello 0" and everything will work as intended. – tshimkus Feb 02 '19 at 16:35
  • The question is: Will you proof, if the user entered anything? If yes, `empty()` is the wrong choice. And who said, that the code is not replicated to other fields like "number of childs". And so the info that `empty("0") === false` is important. For this reason I use always: `isset($a) && strlen($a)`. I know the short cut `@strlen($a)`, but I don't like this kind of error suppression. – Wiimm Feb 02 '19 at 16:44
  • `isset()` will return `false` on `null` values. See https://3v4l.org/HuTjd – stollr Feb 10 '22 at 13:10