Reputation: 311
I'm writing a user login system, and I (like so many others) am having a problem with my sessions.
Here's the pointer from the login script when the inputs are validated:
session_start();
$_SESSION['id']=$id;
header('location: memberhome.php');
Here's the first thing on memberhome.php:
<?php
session_start();
$id=$_SESSION['id'];
?>
And later in memberhome.php:
You are logged in as: <?php echo $id; ?>
The problem is $_SESSION['id'] is apparently empty so the echo $id prints nothing.
An alternate that also does NOT work:
//removed session_start and $_SESSION bit from the top
You are logged in as: <?php session_start(); echo $_SESSION['id']; ?>
NOW, here's the weird part. This method DOES work:
You are logged in as: <?php echo session_start();$_SESSION['id']; ?>
You can see the session_start() is moved AFTER the echo. This works when the page loads from the login script. However, upon refresh, it does NOT work once again.
I've tried a bunch of alternatives and spent a few hours searching for answers in previous questions. I also looked at my phpinfo() for something fishy and found nothing. This is entirely what my progress is hinging on. Thanks!
Upvotes: 2
Views: 2575
Reputation: 12966
You're most likely running into output buffering, which is why it sometimes works and other times it does not. Generally speaking, stick to starting the session before any output is generated, you'll find your code works better.
Upvotes: 0
Reputation: 17598
Make sure you're calling session_start()
before you output anything on the page. The standard cookie-based sessions require some header information to be exchanged, which must be done before you send any content.
Upvotes: 0
Reputation: 2250
First of all, please enable debugging:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Second, session_start() needs to be at the top of the page. So the line you wrote;
You are logged in as: <?php echo session_start();$_SESSION['id']; ?>
will never work.
The following line needs to be on top of the page, before any HTML etc.
<?php
session_start();
$id=$_SESSION['id'];
?>
Upvotes: 1
Reputation: 32126
Have you tried:
print_r($_SESSION);
to examine the contents of the session?
Upvotes: 0