Setting and Destroying SESSION in PHP

Good day everyone! Especially for those who are beginners in PHP. In This tutorial I will teach you Setting and Destroying SESSION in PHP

Are you wondering how login system works in a web based system? We’ll I’ll give you a very simple and meaningful idea on how it works, SESSION using PHP.

So SESSION, is a way to store information (in variables) to be used across multiple pages. This is just like the COOKIE. But unlike the cookie, the information is not stored in the users computer. Meaning when you destroy it. I cannot be retrieved again otherwise start new one.

So let’s start now the first part of this tutorial. I will now teach you in setting a session. Commonly session is used for the login system and for other purposes.

Now create a page for the login form. Then put the html tags needed in the page then inside the body tag. Put this codes for the login.

<form method="post" action="login_action.php">
<label for="username">Username:</label><br>
<input type="tex" name="username" required /><br><br>
<label for="password">Password:</label><br>
<input type="password" name="password" required /><br><br>
<input type="submit" value="login" />
</form>

Inside you login form page before the  “<html>” begin tag, put the PHP code.

<?php session_start(); ?>

This PHP code should be the very first thing before the HTML tags.

When we pass the session variable in the login form it does not mean that it would pass individually in every page of your website. Instead, they are retrieved from the session we open at the beginning of each page. (session_start())

Meaning to say, the “session_start()” should be included in all pages before the HTML tags in order to work the session.

Now we are in the second part of this tutorial. In destroying the session/s.

Create a page, name it as “logout.php” then put the following codes.

[php]<?php session_start(); if ($_session_destroy()) { header(“Location: index.php”); }  ?>[/php]

The codes “session_destroy()” means for destroying the session. Before this php code. The “session_start()” must be the first be written. Then we put the “session_destroy()” in a conditional statement meaning. If the session has been destroyed, the page would be redirect to “index.php”.

That would be all.

If you have questions regarding this tutorial entitled “Setting and Destroying SESSION in PHP”. Feel free to contact us by commenting below or visit on our contact page. Thank you.

Related Article you may Like:

Leave a Comment