注意未定义的索引

时间:2012-10-15 01:52:04

标签: php

  

可能重复:
  PHP: “Notice: Undefined variable” and “Notice: Undefined index”
  Reference - What does this error mean in PHP?

  

注意:未定义的索引:ac在C:\ xampp \ htdocs \ CMS \ includes \ login.php中   在第6行

     

注意:未定义的索引:已登录   第13行的C:\ xampp \ htdocs \ CMS \ includes \ login.php

我收到以上代码的上述通知。如何定义索引?我知道有一种方法可以使用ISSET,但我不知道如何使用$ _SESSION登录和USERS;因为有多个值。如何在不抑制通知/错误的情况下以正确的方式清除上述错误?

<?php
session_start(); // initialize session
include($_SERVER['DOCUMENT_ROOT'] . 
        '/CMS/CMSController.php');

if ($_POST["ac"]=="log") { /// do after login form is submitted  
     if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted username and password exist in $USERS array 
          $_SESSION["logged"]=$_POST["username"]; 
     } else { 
          echo 'Incorrect username/password. Please, try again.'; 
     }; 
}; 
if (array_key_exists($_SESSION["logged"],$USERS)) { //// check if user is logged or not  
    echo "You are logged in.";
    header('Location: /CMS/index.php');
} else { //// if not logged show login form 
     echo '<form action="login.php" method="post"><input type="hidden" name="ac" value="log"> '; 
     echo 'Username: <input type="text" name="username" />'; 
     echo 'Password: <input type="password" name="password" />'; 
     echo '<input type="submit" value="Login" />'; 
     echo '</form>'; 
}; 
?>

2 个答案:

答案 0 :(得分:2)

您可以查看是否与您提及的isset()一起检查了某些内容。像这样使用它:

if(isset($_POST["ac"])) {
    //Code using ac here
}

这样,如果ac索引中没有任何内容,则使用它的代码将执行。 isset本身不会引起通知。

答案 1 :(得分:0)

您可以将其更改为:

<?php
session_start(); // initialize session
include($_SERVER['DOCUMENT_ROOT'] . 
        '/CMS/CMSController.php');

// This is one way to do it - it will give AC a value if it does not exist
// Do this for each $_POST value that may NOT have a value when executing this
// PHP file, for example: $_POST['username'] and $_POST['password']

if (!isset($_POST['ac'])) $_POST['ac'] = FALSE;

OR

// Or you can do it this way
if(isset($_POST['ac'])) {

// The code below will only execute if AC is set

      if ($_POST["ac"]=="log") { /// do after login form is submitted  
         if ($USERS[$_POST["username"]]==$_POST["password"]) { /// check if submitted username and password exist in $USERS array 
          $_SESSION["logged"]=$_POST["username"]; 
       } else { 
            echo 'Incorrect username/password. Please, try again.'; 
       }; 
    };

 // Don't forget the closing curly brace. NO NEED to put ; after the }'s
 }

这些方法中的任何一种都可以正常工作。