DEV Community

Cover image for Understanding Cookies and Sessions in PHP
Dennis Charity
Dennis Charity

Posted on • Updated on

Understanding Cookies and Sessions in PHP

Have you ever wondered how your details and recent activities on a website are being saved and remembered by your system? This happens with the help of cookies and sessions.

In this article, we will discuss what cookies and sessions are, how cookies and sessions work in PHP, How cookies and sessions are created, accessed, modified, and deleted, and the difference between cookies and sessions in PHP.

The Idea Behind Cookies and Sessions in PHP.

If you want to know more about the internet, Cookies and Sessions are two essential things you need to know.

The idea behind them is that they both save the information of the user, such as login details, recent products checked, etc.

Cookies are automatically saved whenever a new web page is opened or reloaded.

Whenever cookies request user information from the server. The server sets a Session ID in the cookies. The server uses that session ID to identify the cookies where the request is coming from.

Image description

What Are Cookies in PHP?

Cookies are small files of information that are sent to a browser to store a user's information from a particular visited website.

Cookies stores user information from a website in the browser only and use that information to identify the user when next the user tries to use visit the same website in the browser

Setting Cookies in PHP

The setcookie() function is used to set a cookie in PHP, it accepts up to six arguments in general, which are all in strings.

Syntax:

---Php
setcookie(name, value, expire, path, domain, secure)
Enter fullscreen mode Exit fullscreen mode

The setcookie() function should be called first before any other code is called or executed, just like the code below:

These are the descriptions of the setcookie() function parameters:

Parameter Description
Name This contains the name of the cookie.
Value This contains the value of the cookie. This could be in a string or integer form
Expire This will contain the expiration date, of the cookie. If omitted, it will take the default value(0s), and immediately after the user reloads or closes the web page the data in the cookies will be lost. Optional
Path This will contain the path of the cookie in the webserver. Optional.
Domain This will contain the domain works. For example, www.example.com. Optional
Secure Optional.

Let's create a PHP file in our code editor(e.g: index.php)

---Php
<?php
    //Setting cookie
    setcookie(name, value, expire, path, domain, secure);
?>
<html lang="en">
 <body>

 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

This previous code is an example that uses the setcookie() function to create a cookie in PHP.

The 'expire' parameter is always calculated in seconds. One day is 86,400 seconds.

The name: 'Username', value: 'Dennis', expire: time() + 86400, path: '/'. we will leave the remaining parameters since they are optional

time() is a function that returns the current time.

Defining your path as /, will make the cookie available to all other domains in our browser.

---Php
<?php
    //Setting cookie
    setcookie('Username', 'Dennis',  time() + 86400, '/');
?>
<html lang="en">
 <body>

 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

How to Access a cookie in PHP

There are different methods you can access a cookie in PHP, but we take the easy method to achieve this by using either $_COOKIE or $HTTP_COOKIE_VARS.

$_COOKIE and $HTTP_COOKIE_VARS are both used to retrieve a cookie value.

The example below shows how we can access a cookie in PHP using $_COOKIE or $HTTP_COOKIE_VARS:

---Php
<?php
    //Setting cookie
    setcookie('Username', 'Dennis',  time() + 86400, '/');
?>
<html lang="en">
 <body>
     <?php
    //Accessing a cookie with $_COOKIE
    echo $_COOKIE["Username"] . "<br/>";

    //Accessing a cookie with $HTTP_COOKIE_VARS
    echo $HTTP_COOKIE_VARS["Username"] . "<br/>";

    ?>
 </body>
</html>
Enter fullscreen mode Exit fullscreen mode

To check if a cookie is set. Use the isset() function.
I will illustrate that in the code below.

---Php
<?php
//Setting cookie
setcookie('Username', 'Dennis',  time() + 86400, '/');
?>
<html lang="en">

<body>
    <?php
    if (isset($_COOKIE['Username'])) {
        echo "The Username is" . $_COOKIE['Username'];
    } else {

        echo "No Username is found";
    }    ?>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

How to Delete a cookie in PHP

The setcookie() function can be used to delete cookies in PHP just the same as creating a cookie. The only difference is to reverse the expiry time to a past time.
The example below illustrates how we can achieve that.

---Php
<?php
//Setting cookie
setcookie('Username', 'Dennis',  time() - 86400, '/');
?>

Enter fullscreen mode Exit fullscreen mode

What Are Sessions in PHP?

Sessions save the user information and activity on a website to a file in a temporary directory on the server. They make user-stored information available across all other websites the browser

This user data are stored temporarily on the server. By default, when a user refreshes or closes the browser the user data vanishes from the server.

How to Start a Session in PHP.

session_start() is a function that is used to start a session in PHP.
PHP $_SESSION is a PHP global variable. It is also an array that stores a session variable whenever a session creates a temporary file in the server.

Let's start a new PHP session and set a few session variables to the $_SESSION :

---Php
<?php
session_start();
?>

<!DOCTYPE html>
<html lang="en">
<body>
    <?php
    $_SESSION["name"] = "Dennis";
    ?>
</body>

</html>

Enter fullscreen mode Exit fullscreen mode

How to Get a Session Variable Values and display it

Here, we will get the Session variable from the previous code.
View this example to get a better understanding:

---Php
<?php
 session_start(); 
?>
<!DOCTYPE html>
<html>

<body>
    <?php
    // This will display the name from the previous code
    echo "My name is " . $_SESSION["name"];
    print_r($_SESSION);
    ?>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

How to Modify a Session Variable

Overwrite the session variable with this code below whenever it is necessary.

---Php
<?php
session_start();
?>
<!DOCTYPE html>
<html>

<body>

    <?php
    // Overwrite the session variable here.
    $_SESSION["name"] = "Charity";
    print_r($_SESSION);
    ?>

</body>

</html>
Enter fullscreen mode Exit fullscreen mode

How to destroy a session in PHP.

To remove all variable values from a session, you have to make use of two functions, session_unset() and session_destroy(). These functions have different purposes.
Follow this example below:

---php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// This is to remove all session variables
session_unset();

// This is to destroy the session
session_destroy();
?>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Differences Between Cookies and Sessions in PHP.

These are a few differences between cookies and sessions in PHP:

Cookies Sessions
Cookies stores user data in the browser Sessions stores user data in the server
Cookies store user data permanently till the user decides to discard it Sessions stores user data temporarily and dispose of it when the user refreshes or closes the browser.
Cookies can easily be accessed by hackers since it stores user data in the browser Sessions cannot be accessed by hackers since it stores a user data on the server
Cookies contain a minimal amount of storage space(4kb) to store user data Sessions contain a large amount of storage space(128MB) to store user data

Conclusion

We learned what Cookies and Sessions are in PHP, their purpose, How they work, and the difference between them. I hope this was helpful. Thank you for taking the time to read this.

Discussion (1)

Collapse
suckup_de profile image
Lars Moelleken

"Sessions cannot be accessed by hackers since it stores user in the server".

⇐ This is only valid if you protect your PHPSESSID Cookie. Every developer should try this: login into a PHP bases web application and copy and past the cookie into a different Browser, mostly you will be logged-in into your account without any password