How to Start Session in PHP: Simple Guide with Examples
To start a session in PHP, use the
session_start() function at the very beginning of your script before any output. This function initializes a session or resumes the current one, allowing you to store and access user data across pages.Syntax
The basic syntax to start a session in PHP is simple:
session_start();- This function must be called before any HTML or output is sent to the browser.
It initializes a new session or resumes an existing one, enabling you to use the $_SESSION superglobal array to store user data.
php
<?php session_start(); ?>
Example
This example shows how to start a session, store a value, and then access it on the same page.
php
<?php session_start(); // Store data in session $_SESSION['username'] = 'Alice'; // Access and display session data echo 'Hello, ' . $_SESSION['username'] . '!'; ?>
Output
Hello, Alice!
Common Pitfalls
Common mistakes when starting sessions include:
- Calling
session_start()after outputting HTML or whitespace, which causes errors. - Not calling
session_start()on every page where session data is accessed. - Forgetting to check if session variables exist before using them.
php
<?php // Wrong: output before session_start() echo 'Welcome!'; session_start(); // Causes error // Right: session_start() first session_start(); echo 'Welcome!'; ?>
Quick Reference
Remember these tips when working with PHP sessions:
- Always call
session_start()at the very top of your script. - Use
$_SESSIONto store and retrieve session data. - Sessions help keep user data across multiple pages.
Key Takeaways
Always call
session_start() before any output to start or resume a session.Use the
$_SESSION array to store and access user data across pages.Call
session_start() on every page where you want to use session data.Avoid sending any output before
session_start() to prevent errors.Check if session variables exist before using them to avoid warnings.