0

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?

0

2 Answers 2

4

Your error is simple .

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

You are trying to use $username before assigning it.

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

Should be better !

Sign up to request clarification or add additional context in comments.

2 Comments

There isn't any stupid question, dont forget to mark your question as resolved :)
I will do, need to wait a few minutes to do so though. Thanks again!
0

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 : '';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.