PHP Sessions

PHP Tutorial

PHP Sessions Tutorial

PHP sessions allow you to store user information on the server and access it across multiple pages. Unlike cookies, sessions are more secure because data is not stored on the client-side.


 Starting a Session

Before using sessions, you must call session_start() at the top of the PHP page (before HTML output):


 

  • $_SESSION is an associative array storing session data.

  • Sessions are identified by a unique session ID.


 Accessing Session Variables


 

 Session variables are available on all pages where session_start() is called.


 Modifying Session Variables


 


 Removing a Single Session Variable


 


 Destroying a Session


 

  • After session_destroy(), session variables are no longer available.

  • Useful for logout functionality.


 Example: Login Simulation with Session

login.php


 

dashboard.php


 

logout.php


 


 Key Points

  1. Sessions are stored on the server → more secure than cookies.

  2. Use $_SESSION array to store and retrieve data.

  3. session_start() must be called before any HTML output.

  4. Use unset() to remove a single variable and session_destroy() to remove all session data.

  5. Useful for login systems, shopping carts, and user preferences.

You may also like...