Kaly
Kaly

Reputation: 3599

PHP session variable not being set

I am aware that there are several topics about this but after hours of reading I still can't figure out what's going wrong.

I'm building a survey with a login screen at index.php. The user is required to insert their name and submit the form. The username should be saved and passed onto setup1.php.

This is part of my index.php:

<?php
    session_start();
    print session_id();
?>
<form id="login" method="POST" action="setup1.php">
<input id="participant" name="participant" type="text" size="20"/>
<input type="submit" name="start" value="Start"/>
</form>
<?php
    $name = $_POST['participant'];
    $_SESSION['username'] = $name;
?>

Start of setup1.php:

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

My $_SESSION variable is empty, I have nothing printed on the following page setup.php. I would appreciate if you could help.

Upvotes: 0

Views: 3097

Answers (3)

Lakin Mohapatra
Lakin Mohapatra

Reputation: 1135

index.php

<?php session_start(); ?>

<form id="login" method="POST" action="setup1.php"> <input id="participant" name="participant" type="text" size="20"/> <input type="submit" name="start" value="Start"/> </form>

setup1.php

<?php session_start();

if(isset($_POST['participant']) && ! empty($_POST['participant'])) { $_SESSION['username'] = $_POST['participant']; echo $_SESSION['username']; } ?>`

Upvotes: 0

Albzi
Albzi

Reputation: 15609

Your $_POST code is in the wrong file. Your form is going to setup1.php, but you're trying to set the $_SESSION in your index.php.

You need to take it out of there and put it in setup1.php:

<?php
  session_start();

  if (!isset($_POST['participant'])) {
    die('No $_POST data');
  }

  $_SESSION['username'] = $_POST['participant'];

  print session_id();
  print_r($_SESSION);
  echo $_SESSION['username'];
?>

Also, make sure that you're using $_SESSION and not %_SESSION. I hope it was just a typo.

Upvotes: 5

Akshay Khetrapal
Akshay Khetrapal

Reputation: 2676

Your form hasn't been submitted when you set the $_SESSION['username'], i.e., $_POST['participant'] has no value.

You should move the piece of code below from index.php to setup1.php

<?php
$name = $_POST['participant'];
$_SESSION['username'] = $name;
?>

Upvotes: 0

Related Questions