Sessions

Gajindu Bandara
1 min readFeb 10, 2022

Sessions are something alike cookies the main use of these sessions is to keep the record of the users. But the sessions are better than the cookies.

What is a session?- Session variables are used to store information about the users and those data can be passed across the pages easily.

The session starts with the “Session_start()” and we can assign the values to a session. As the first step we must have a new session with a variable name for that we can have the session like this “$_SESSION[“variable name “]”.

After the task, the sessions must be destroyed so, in the end, we should destroy the sessions. For that, we can use “Session_unset ” or “Session_remove”.By using unset we can remove all the session variables and by using destroy we can destroy all the sessions.

Now I'm gonna show an example about working with sessions. In this code after giving an input, the input value will be assigned to a session and the session will display the assigned value on the screen. Also, in the end, the session will be removed.

<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Session test</title>
</head>
<body>

<form method="post">
<input type="text" placeholder="name" name="Name">
<input type="submit" value="Submit" name="Submit">
</form>
<?php
if($_SERVER["REQUEST_METHOD"] = "POST"){
if (isset($_POST["Submit"])) {
$_SESSION["name"] =$_POST["Name"]];
echo $_SESSION["name"];
}
unset($_SESSION["name"]);
}
?>
</body>
</html>

So that’s it you can simply use these sessions for your projects 😃

--

--