PHP Sessions

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.


1️⃣ 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.


2️⃣ Accessing Session Variables


 

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


3️⃣ Modifying Session Variables


 


4️⃣ Removing a Single Session Variable


 


5️⃣ Destroying a Session


 

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

  • Useful for logout functionality.


6️⃣ Example: Login Simulation with Session

login.php


 

dashboard.php


 

logout.php


 


7️⃣ 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.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *