PHP Session

A session is a way to store information across multiple pages. In PHP, that information is stored in a $_SESSION global variable. session_start(); function is used to create new session that will be used on different pages.

Let's create two php pages and see how we can set and access session variables across multiple pages.

//page-one.php session_start(); //create new session //set session variables in a $_SESSION global array variable $_SESSION[ 'username' ] = 'worker'; $_SESSION[ 'role' ] = 'author'; print_r( $_SESSION ); //output: Array ( [username] => worker [role] => author )

We can then access session variables on another page:

//page-two.php session_start(); //must be used on all pages that use session print_r( $_SESSION ); //output: Array ( [username] => worker [role] => author ) //change session variables $_SESSION[ 'username' ] = 'clevertechie'; $_SESSION[ 'role' ] = 'admin'; print_r( $_SESSION ); //output: Array ( [username] => clevertechie [role] => admin ) session_destroy(); //note: this will clear $_SESSION next time it's accessed

When we try to print out $_SESSION on the next page, we get an empty array, because the session was destroyed with session_destroy() on previous page.

//page-three.php session_start(); //create new session print_r( $_SESSION ); //output: Array ( )