Undefined index errors in PHP form submission code

I keep getting undefined index to this. When I take the bug report everything is fine, but I am looking for a way to fix it "RIGHT WAY"

In my form at register.php, the button looks like this:

<input type="submit" name="submit" class="btn btn-kani btn-lg" value="Sign Up"/>

      

Then it is linked to another page called login.php

Login.php code

I tried

if (isset($_POST['submit']=="Sign Up")) {
// etc.

      

I tried

if ($_POST['submit']=="Sign Up") { 
// etc.

      

Same with session logout due to session, not sure how it should be encoded ... Button reads

<li class="inactive"><a href="logout.php?logout=1">Log Out</a></li>

      

and the code in login.php

if($_GET["logout"]==1 AND $_SESSION['id']) {
    session_destroy();
    header("Location:../logout.php");       
}

      

+3


source to share


2 answers


No isset()

evaluates what's inside and tells you if its true or false:

So this expression doesn't make much sense in what you are trying to do:

if (isset($_POST['submit']=="Sign Up")) {

      

Should be:

if(isset($_POST['submit'])) { // if index submit <input type="submit" name="submit" /> button was pressed
    // so if the button is pressed, then it will go inside this block
}

      



If you want to appreciate its presence and meaning, you can do something like:

if(isset($_POST['submit']) && $_POST['submit'] == 'whatever value') {

}

      

As for the session, you can check it like this:

if(isset($_GET['logout'], $_SESSION['id']) && $_GET['logout'] == 1) {
    // if both get logout and session id does exists and logout is equal to 1
    session_destroy();
    header('Location: ../logout.php');
}

      

If you need more information, you can check out deceze The Ultimate Guide to PHP isset AND empty . It's a good read, and explains eloquently how to use it in test cases similar to yours

+2


source


if ($_POST['submit']=="Sign Up")

does not check first to make sure the value is in $_POST['submit']

, which could result in "undefined index";

if (isset($_POST['submit']=="Sign Up"))

just doesn't make sense. Try something like:



if (isset($_POST['submit']) && ($_POST['submit']==="Sign Up"))

+1


source







All Articles