Table of Contents

PHP Sessions

Using a session allows us to save a piece of data across multiple pages. Let's go to our index.php and create our first session.

The first thing you have to do is run a function called session_start at the beginning of our file. This essentially lets the application know that we want to start sessions, we want to be able to store sessions, and then we also want to be able to keep them for the next request. These sessions are actually stored on the server-side, and then it leverages cookies so that way it can maintain the session ID between the client and the server.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>My First PHP App</titile>
</head>
<body>
   
    <h1>Home Page</h1>

   <?php $_SESSION['name'] = 'DevDojo'; ?>
   <?php echo $_SESSION['name']; ?>

</body>
</html>

Now let's go to our welcome.php and echo out our session name there.

<?php
    session_start();
?>
<!DOCTYPE html>
<html>
<head>
    <title>My First PHP App</titile>
</head>
<body>
   
    <h1>Welcome Page</h1>

   <?php echo $_SESSION['name']; ?>

</body>
</html>

It will still echo out our session because it is set in our home page, and then we should be able to echo out what inside $_SESSION.