Setting and Destroying SESSION in PHP

0
58

Good day everyone! Especially for those who are beginners 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 logged in 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.

  1. <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.

  1. &lt;?php session_start(); ?&gt;

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 passed indivually in every pages of your website. Instead they are retrieved from the session we open at the beginning of each pages. (session_start())

Meaning to say, the “session_start()” should be include 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.

  1. &lt;?php session_start(); if ($_session_destroy()) { header("Location: index.php"); }  ?&gt;

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:

Facebook Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here