Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Form Validation with isset() function

Tags:

php

Code from Robin Nixon book:

<?php
if (isset($_POST['name'])) $name = $_POST['name'];
else $name = '(enter your name)';
echo <<<_END
<html>
    <head>
        <title>Test</title>
    </head>
    <body>
    Your name is $name<br />
    <form method = 'post' action = 'count.php'>
        What's your name?
        <input type='text' name='name' />
        <input type='submit' />
    </form>
    </body>
</html>
_END
?>

In the second line we check is variable set or not with isset(). In the third line we have a condition: if it's not set, the script prints 'enter your name'. That's what I do not understand: I open this page - it prints:

Your name (Enter your name) What is your name? (and the submission form)

Did not enter nothing at all, then hit "send" - it prints:

Your name is (and does NOT print "Enter your name") What's your name? (and the submission form)

I didn't enter anything but the function said that the variable was set to a value other than NULL. Why? If it passes an empty value, then why use it? Why just not use empty? But in all programs I see solution like this. Why do we have to use isset() function there? What don't I understand?

like image 811
9Algorithm Avatar asked Aug 15 '26 19:08

9Algorithm


1 Answers

The isset function is used to check if the text-field <input type='text' name='name' /> has any data submitted via POST which is captured in $_POST['name'].

When you submit the form, the $_POST['name'] is blank, or an empty string. Hence, you see Your name is What's your name? (and the submission form), as isset evaluated to true for an empty string.

If you want to check for the emptiness of the text-field, you should use empty() function, which checks for both isset and well as if the field is blank/empty.

  if (!empty($_POST['name'])) $name = $_POST['name'];
  else $name = '(enter your name)';
like image 200
Teena Thomas Avatar answered Aug 17 '26 12:08

Teena Thomas