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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<?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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php session_start(); ?> <!DOCTYPE html> <html> <body> <?php session_unset(); session_destroy(); ?> </body> </html> |
No Comments