CommonLounge Archive

PHP: Sessions, Include and Require

September 19, 2018

To start playing with the upcoming concepts in PHP, let’s create a new folder inside {your_xampp_directory}/htdocs and call it advanced.

Remember: By default, {your_xampp_directory} is located in C:\xampp\ in Windows, /opt/lampp/ in Linux and /192.168.64.2/lampp/ in OS X.

Session

Let’s say you visit Twitter, Facebook, Commonlounge (😉), or any of your other favorite websites. If you open multiple tabs, or you close your current tab and open it again in five tabs, you’ll notice that you don’t get logged out if you were already logged in. Even on a website where you are not required to log-in, some information is often preserved from one tab to another, or if you close the tab and re-open in a few minutes.

On internet applications, this information is preserved using the concept of sessions. A session is a way to store information about a single user (like userid, username, etc.) to be used across multiple pages.

In PHP, this is done using the $_SESSION superglobal array. By default, session variables last until the user closes the browser.

Starting a PHP Session

A PHP session is easily started by calling the session_start() function. This function first checks if a session is already started and if not, it starts one.

It is recommended to put the call to session_start() at the beginning of the PHP code. Open up your code editor and write this code:

<!-- page1.php -->
<?php
    session_start(); // starting the session
?>
<html>
<body>
<?php
    $_SESSION["userid"] = 1;
    $_SESSION["username"] ="Commonlounge";
    echo "Session started";
?>
</body>
</html>

Save this file as page1.php. Open your browser and go to http://localhost/advanced/page1.php (for OS X, replace localhost with the IP address you had).

You will see:

Session started

Great! PHP just started a session for us and using the superglobal associative array $_SESSION, it set the userid and username keys to 1 and Commonlounge respectively.

The main purpose of storing these values is to use them across multiple pages. So let’s go ahead and create another PHP file and call it page2.php:

<!-- page2.php -->
<?php
    session_start(); // starting the session
?>
<html>
<body>
<?php
    echo "Your id is: " . $_SESSION["userid"] . "<br>";
    echo "Your username is: " . $_SESSION["username"];
?>
</body>
</html>

Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page using the session_start() function.

Now save the file and go to http://localhost/advanced/page2.php in your browser:

Your id is: 1
Your username is: Commonlounge

Amazing, right? page2.php knows that page1.php has started a session and set certain values in a session variable and page2.php can access those values just by using the superglobal $_SESSION!

How does page2.php know that page1.php started a session?

PHP first creates a unique identifier for a particular session which is a random string of 32 hexadecimal numbers. Then, when a session is opened on another page, it scans the computer for an identifier. If there is a match, it accesses that session, if not, it starts a new session.

Modifying a PHP Session

To change a session variable, we can simply overwrite it. We can also make use of the isset() function to check if session variable is already set or not.

<!-- page2.php -->
<?php
    session_start(); // starting the session
    if (isset($_SESSION["username"])) {
        $_SESSION["username"] = "Dave";
    }
?>
<html>
<body>
<?php
    echo "Your id is: " . $_SESSION["userid"] . "<br>";
    echo "Your username is: " . $_SESSION["username"];
?>
</body>
</html>

Since username was already set to Commonlounge, the isset() function returns true and the session variable is modified.

This will output.

Your id is: 1
Your username is: Dave

Destroying a PHP Session

A PHP session can be destroyed by using the session_destroy() function. This function does not need any argument and a single call will destroy all the session variables:

<?php
   session_destroy();
?>

If you want to unset a single session variable then you can use unset() function:

<?php
   unset($_SESSION['username']);
?>

When do we delete a session? Generally, we start a session when a user logs in to a website and we destroy the session when the user logs out. You might have noticed this on sites like Facebook, Twitter and even Commonlounge. Easy, right?

Include and Require

Okay, so now we started dealing with multi-page websites in PHP! Let’s say we want to include the same PHP, HTML, or text on multiple pages of a website. Done naively, we would have to copy-paste the code again and again in every file. This becomes very tedious and is considered a bad practice while coding.

Luckily, PHP allows us to tackle this problem with include and require statements. The include (or require) statement takes all the text / code / HTML that exists in the specified file and copies it into the file that uses the include statement.

Let’s look at an example. We want to create a menu for our website which will be part of every page. So go ahead and create a file menu.php:

<!-- menu.php -->
<a href="">Home</a> - 
<a href="">About</a> - 
<a href="">Photos</a> - 
<a href="">Profile</a> <br />

We can now include this file from any PHP file and we will have our menu ready without having to write the code again! For example, let’s create a test.php file with the following code:

<!-- test.php -->
<html>
    <body>
        <?php 
            include "menu.php"; 
        ?>
        <p>This is how we include a PHP file!</p>      
    </body>
</html>

Save the file and go to http://localhost/advanced/test.php in your browser:

Home - About - Photos - Profile
This is how we include a PHP file!

The require statement works the same way as the include statement:

<?php 
    require "menu.php";
?>

However, there is one major difference between include and require; when a file is included with the include statement and PHP cannot find it, the script will continue to execute:

<!-- test.php -->
<html>
    <body>
        <?php 
            include "someFile.php"; 
        ?>
        <p>This is how we include a PHP file!</p>      
    </body>
</html>

This will give a warning, but the execution will continue and we will see the output:

Warning: include(): Failed opening 'someFile.php'...
This is how we include a PHP file!

If we do the same example using the require statement, we get a Fatal error and the echo statement will not be executed:

Fatal error: require(): Failed opening required 'someFile.php'...

Almost all multi-page websites using PHP make use of include statements (and sometimes require) to reduce code redundancy and maintain modularity.

Include Once

The include_once statement is similar to the include statement, with the only difference being that if the code from a file has already been included, it will not be included again, and include_once returns**TRUE**.

Take this example:

<!-- test.php -->
<?php
    include_once "menu.php"; 
?>
<html>
    <body>
        <?php 
            include_once "menu.php"; 
        ?>
        <p>This is how we include a PHP file!</p>      
    </body>
</html>

Here, we are including menu.php twice. Since we used include_once instead of include, the menu will only be displayed once.

Home - About - Photos - Profile
This is how we include a PHP file!

include_once comes in handy for large projects, where multiple files need to include the same file, but importing the file multiple times causes errors.

Summary

You just learned some core PHP features like Session, Include and Require with which you can create a multi-page websites!


© 2016-2022. All rights reserved.