Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined index errors in PHP form submission code

Tags:

html

php

mysql

I keep getting an undefined index to this..When I take error reporting off, all is good, but I am looking for a way to fix this the "RIGHT WAY"

On my form on register.php, the button looks like this

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

This is then linked to another page called login.php

Login.php code

I have tried

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

I have tried

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

Same with the logout because of the session, not sure how it should be coded....The button reads

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

and the code on login.php

if($_GET["logout"]==1 AND $_SESSION['id']) {
    session_destroy();
    header("Location:../logout.php");       
}
like image 511
Kim N Anthony Stole Avatar asked Jan 19 '26 11:01

Kim N Anthony Stole


2 Answers

No isset() evaluates whats inside and tells you if its true or false:

So this expression doesn't make really sense on what you're trying to do:

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

Should be like:

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 evaluate its presence and value you could do something like:

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

}

Regarding the session you could 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 want more supplemental info, you could check out deceze's The Definitive Guide To PHP's isset And empty. This is a good read and eloquently explains how to use it with test cases, similar to yours

like image 196
Kevin Avatar answered Jan 22 '26 00:01

Kevin


if ($_POST['submit']=="Sign Up") does not check first to make sure there's a value in $_POST['submit'], which can result in "undefined index";

if (isset($_POST['submit']=="Sign Up")) just doesn't even make sense. Try something like:

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

like image 43
TML Avatar answered Jan 22 '26 00:01

TML



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!