Reputation: 4702
I'm trying to get a user on my web shop to enter a username which will then be displayed on each page. I've started the session here in header.php and set the username variable:
session_start();
$_SESSION['username'] = $username;
$username = ''; //set blank variable to be filled in index
I'm then calling header.php in index.php using:
<?php
include "header.php";
?>
Inside of the logIn div I'm then asking for the username to be entered (no form to submit it yet, haven't gotten that far without running into the problem below). The script should show a message if the user isn't logged in alongside a form to log in, but if they have submitted a username to use then the form should display a welcome message:
<div class="logIn">
<?php
if (!isset($_SESSION['username'])) {
echo 'Welcome, '.$_SESSION['username'];
} else {
echo 'Sorry, You are not logged in.';
}
?>
</div>
I'm currently getting this error:
Notice: Undefined variable: username in /header.php on line 13
but I can't figure out why. I thought I'd declared it as empty, but even when I give it a value the if statement in index.php isn't working as intended.
How can I set up a simple session and accept a username variable (no password) which will then be displayed on index.php?
Upvotes: 0
Views: 46
Reputation: 2792
I guess line 13 is this one $_SESSION['username'] = $username;
?
If you are assigning $username
to $_SESSION['username']
it must be set somewhere before, I can't see that in your example.
Your code has to look something like this:
//declare $username
$username = "somename";
$_SESSION['username'] = $username;
Or if you set $username
in a condition or something else you can try this:
$_SESSION['username'] = ( isset( $username ) ) ? $username : '';
Upvotes: 0
Reputation: 1345
Your error is simple .
$_SESSION['username'] = $username;
$username = '';
You are trying to use $username
before assigning it.
$username = '';
$_SESSION['username'] = $username;
Should be better !
Upvotes: 4