27

Here is my php code:

<?php include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Member Index</title>
<link href="css/main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Welcome <?php echo ($_SESSION['SESS_fname']);?></h1>
<a href="member-profile.php">My Profile</a> | <a href="logout.php">Logout</a>
<p>This is a password protected area only accessible to members. </p>
</body>
</html>

I know something I wrong with the code but I don't know how to fix it. My error says: "Notice: Undefined variable: _SESSION in C:\xampp\htdocs\Smasher\member-index.php on line 9"

How can I fix the error so it will say the user's first name? The first name in the database table on mySQL is called fname.

jhoyla
  • 1,191
  • 1
  • 9
  • 26
user2203600
  • 373
  • 2
  • 4
  • 6
  • @mario. Same basic problem, but that one was specific to CakePHP and its session helper. (See the accepted answer to that question, which wouldn't help this user at all.) – TRiG Mar 24 '13 at 02:42

2 Answers2

44

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Yassir Ennazk
  • 6,970
  • 4
  • 31
  • 37
8

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");
What have you tried
  • 11,018
  • 4
  • 31
  • 45
  • 2
    Not obvious for beginners coming here for tips. Between tags like: `` – mLstudent33 Oct 07 '20 at 07:16
  • This should be the accepted answer because of that "at the top of ***any page*** that you wish to use SESSION variables". If you are passing between a.php, b.php and c.php, you need to open the session at the top of all three. It is a common beginner mistake to only open it on the first page. – Mawg says reinstate Monica May 03 '21 at 07:18
  • Also, don't forget to call `session_unset()` and `session_destroy()` at then of the last page ***and*** is any `catch (Exception $e)`, to tidy up – Mawg says reinstate Monica May 03 '21 at 07:19