yamahamm
yamahamm

Reputation: 103

Session variable isnt returned

I got 2 php files. I want to send $myusername from one page to another. I use $_SESSION in the first one, but it still doesn't appear on the second page.

First page:

<?php
  $username=$_POST["username"];
  $count=mysqli_num_rows($result);

  if($count==1){
    header("location:the_cave.php");
    session_start();
    $_SESSION['username'] = $username;
  }
?>

Second page:

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

and then I want to use JS to put it into a span. but span remains empty.

document.getElementById("username").innerHTML="<?php echo $username;?>";

Upvotes: 1

Views: 44

Answers (2)

display-name-is-missing
display-name-is-missing

Reputation: 4399

You need to start the php code on page one with:

session_start();

Thus, try this code on the first page:

<?php

  session_start();

  // all the other php code

  $username=$_POST["username"];
  $count=mysqli_num_rows($result);

  if($count==1){
    $_SESSION['myusername'] = $username;
    header("location:the_cave.php");
    exit();
  }

?>

and to put the username into a span on the second page, just use this code:

<span id="username"><?php echo $_SESSION['username']; ?></span>

Upvotes: 2

Akhil Sidharth
Akhil Sidharth

Reputation: 746

Have you started session in the first page using session_start() before putting values in session ? if you did, try echo $username=$_SESSION['username']; in the second page before using javascript just to confirm you are getting the desired result.

Upvotes: 0

Related Questions