0

Notice: Undefined index: register on line 12.

This is some old website code that I'm going through to fix - I'm a noob at this.

Originally I was using isset(), but was forced to use null!==

if (isset($_SESSION['id'])) {    
    echo "<fieldset><legend><b>Error!</b></legend>";
    echo "You are already logged in, therefore you can not register a new account!";
    echo "</fieldset>";
} else {
    if (null !== (!$_POST['register'])) {
        echo "<fieldset><legend><b>Registration</b></legend><br />";
        echo "Fill out all of these fields below in order to create a new account. This account will be used to enter, so you are advised not to share the information with anyone at all!<br /><br />";
        echo "<form method=\"POST\">";

I expect to get a working registration form, but get this. I get the same undefined index error in other files as well in similar scenarios.

Bulat
  • 720
  • 7
  • 15
unnqca
  • 9
  • 1
  • 1
    `null !== ` only checks if the value isn't null. It's not a substitute for `isset()`, which also checks if the variable is _defined_ (which it doesn't seem to be in your case). So you would still need to check if the variable (or array index) exists and is defined before you try and use it. – M. Eriksson Jun 19 '19 at 06:04
  • 1
    Possible duplicate of ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – M. Eriksson Jun 19 '19 at 06:07
  • @MagnusEriksson I can't use isset() because its the result of an expression error: Fatal error: Cannot use isset() on the result of an expression (you can use "null !== expression" instead) – unnqca Jun 19 '19 at 06:31
  • 2
    No one said you should try and check a whole expression with isset, you check if the variable is set. If you need to check additional stuff _after_ you have made sure it is set, then do that. `if( isset($_POST['register']) && …)` – 04FS Jun 19 '19 at 07:22
  • Simply doing `isset($_POST['register'])` will check if the variable is defined (exists at all) and isn't `null`. So all you need is: `if (isset($_POST['register'])) { ... }`. That's it since `isset()` already includes the `null !==`-check. – M. Eriksson Jun 19 '19 at 08:45

1 Answers1

0

Replace

if (null !== (!$_POST['register']))

with

if (isset($_POST['register']) && $_POST['register'] != '') // to check not empty

or if (isset($_POST['register']))

Checking isset() will check if the index is defined. If needed to check if any value exists in the index check $_POST['register'] != ''

While using such scenarios it is always best to check if the index is present and the value in the index is defined. This will save a lot of headaches.

Lublaut
  • 339
  • 4
  • 11