-1

On the form page I have the following:

<?php
session_start();
if (isset($_POST['submit'])){
   $_SESSION['username'] = $_POST['username'];
}
?>
<form action="index.php">
<input type="text" name="username">
<input type="submit" name="submit">
</form>

On the file 'index.php' I have:

<?php
session_start();
echo ($_SESSION['username']);
?>

But the output on the index page says that the session variable is undefined. How do I fix this and why is it undefined?

  • 2
    Is there _anything_ else on either of these pages? I presume there is more HTML that came before the form and `session_start()` and if that's the case, you are suffering from the "Headers already sent" error. Enable error display, always when developing and testing code. At the top of both scripts: `error_reporting(E_ALL); ini_set('display_errors', 1);` Your answer most likely likes [with How to fix Headers already sent](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) where you'll need to move `session_start()` to occur before _any_ output of any kind – Michael Berkowski Dec 21 '17 at 15:16
  • 6
    the form is submitted to your `index.php`, so you need to retrieve the `$_POST` information there, not in your `form.php` (or however you called it) – William Perron Dec 21 '17 at 15:17

1 Answers1

5

Your form is submitted to the index file and you are trying to set the session on the same page as the form. But you need to set the session in the index file. after that you can use the session on other pages.

Dave
  • 290
  • 2
  • 12