Terry J.
Terry J.

Reputation: 9

How to use $_SESSION in a included file

On every page that I access through index2.php, where my game is but the header file is included there. Do I need to use $username = $_SESSION['username'] in every page if I have it in the header file? How do I do it?

Upvotes: 1

Views: 75

Answers (2)

prince efenure
prince efenure

Reputation: 1

session_start();

  $username = 'guest';

if(isset($_SESSION['username']))
{
    $username = $_SESSION['username'];    
}


require_once("path_to_session.php")

Upvotes: 0

Kaboom
Kaboom

Reputation: 684

The short answer is if you include a page at the top of your script and it is defining the $username variable as the $_SESSION var, then no you do not need to set it on every page. However, that being said make sure you are checking to see if the session is set before setting it.

Example is if the user is guest you can do the following:

$username = "guest";
if(isset($_SESSION['username'])) {
    $username = $_SESSION['username'];
}

Since your question was updated to ask how you do it you include the file using the following

include_once("path/to/file.php");

Upvotes: 1

Related Questions