Jay Gould Jay Gould - 1 year ago 75
PHP Question

empty() check not validating after POST

I'm setting a session variable in my

header.php
here:

<?php

session_start();

if(empty($_SESSION['name'])) {
?>
No name set! <br>
<form action="" method="post">
<input type="text" name="textName"/>
<input type="submit" name="submitName" value="Log in"/>
</form>

<?php
if(isset($_POST['submitName'])) {
$_SESSION['name'] = $_POST['textName'];

}
}


and validating that the
name
variable is set on my index here:

<?php

include 'header.php';

if(!empty($_SESSION['name'])){
?>
<a href="session_kill.php">Log out</a>
<?php
}

?>


I can confirm that the session variable exists because the
logout
link appears.

After submitting a name via the form, the session variable updates but the
empty()
check doesn't reoccur, meaning the
textarea
stays on the page unless I refresh.

Can anyone tell me why this happens?

Answer Source

Take this part:

if(isset($_POST['submitName'])) {
    $_SESSION['name'] = $_POST['textName'];

}

above this:

if(empty($_SESSION['name'])) {}

When you submit the form, at the beginning; since the session is empty and hence the form remains there and then the session is initialized. And when you refresh the page the session check works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download