08 Jul PHP Sessions
PHP Sessions stores information across the various pages of a website. A file gets created in a temporary directory on the server. In the file, registered session variables and values get stored. In this lesson, we will see how to:
- Start a session in PHP
- Delete a session in PHP
Start a session
We will learn how to start a session. The method session_start() starts a session and the isset() function checks if the session variable is set or not.
Let us now see an example to start a session in PHP:
<?php
session_start();
if( isset( $_SESSION['num'] ) ) {
$_SESSION['num'] = $_SESSION['num'] + 1;
}else {
$_SESSION['num'] = 1;
}
$result = "Accessed the page ". $_SESSION['counter'];
$result .= "time/times.";
?>
<html>
<body>
<?php
echo ( $result ); ?>
</body>
</html>
Here’s the output,

Destroy a session
Create as well as destroy PHP sessions with ease. With PHP, easily delete all the sessions and session variables. For that, we will be using the following two methods,
- session_unset( ): to remove session variables,
- session_destroy(): destroys the session
Let us see an example to destroy a session:
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php session_unset(); session_destroy(); ?> </body> </html>
No Comments