Search code examples
phpvariablesif-statementisset

PHP - how to get rid of "Undefined index"


I wasn't able to find a solid work-a-round yet for it so I thought I just might ask here.

My error.log says for a good reason

[error] [client xxx.xxx.xxx.xxx] PHP Notice:  Undefined index: Variablename

Till now I got rid of it with using a if statement around it like

if (isset($var)) {
  if ($var ... ) { ... }
}

But now I got a lil problem so I can't use this "wrap-around" like above easily.

the check_login(...) function will write $_SESSION Variables like ['loginattempts'] or ['captchaattempts'] - now I want to let the login disappear if those attemps reach a specified amount. Like

if ($_SESSION['loginatt'] < x && $_SESSION['capatt'] < x) { echo 'login form...';}

If I would wrap a check if the variable is set around it - the login wouldn't appear if those variables are not set.

Possible work-a-rounds could be

if (!isset($var)) {echo 'login form ...';}
else {echo 'login form...';}

but that would mean I would have to have a duplicate login form in my code I know could also just change this echo 'login form ...' into a requice_once 'include/loginform.php' - but there would be still a duplicate entry for this require_once command.

I could also set a $testvar like

if (isset($var)) { 
  if ($var > x) {
    echo 'acc. blocked;
    $testvar = 0;
  }
  else {
    $testvar = 1;
  }

if ($testvar < 1) {
  echo 'login form...';
}

So are there any other ways as those ?

If not which way you would suggest to take to keep the code as it should be for "good programming" ?

Any statements are welcome, thanks for helping out

Kris


Solution

  • In my experience, it's always a good idea to output all errors during development and to always have initialized values. It can get rid of some bugs as you will always have a default value to fall back on.

    An easy way to fix your problem is to use another variable and to add your $_SESSION variables only if they exist. For instance:

    $login_attempts = 0;
    if (isset($_SESSION['loginattempts'])) {
        $login_attempts = $_SESSION['loginattempts'];
    }
    

    Alternatively, a ternary expression is also possible for compactness, although with the long loginattempts index this looks a little harsh, in my opinion.

    $login_attempts = (isset($_SESSION['loginattempts'])) ? $_SESSION['loginattempts'] : 0;