Start a Session in PHP
In PHP, you start a session by using the session_start()
function. This function must be called at the beginning of your script before any output is sent to the browser. Here's a simple example:
<?php
// Start the session
session_start();
// Now you can set or retrieve session variables
$_SESSION['user_id'] = 123;
$_SESSION['username'] = 'john_doe';
// Rest of your PHP code
?>
In this example:
The session_start()
function initiates or resumes a session. It should be called before accessing or modifying any session variables.
After starting the session, you can use the $_SESSION
superglobal to store and retrieve session data. The data stored in $_SESSION
will be available across different pages for the same user during the session.
Remember to call session_start()
on every page where you want to access or modify session variables. Typically, this includes every page that is part of your application and needs to maintain user state.
Here's a basic example of starting a session and displaying session data on another page:
Page 1 (start_session.php
):
<?php
session_start();
echo "User ID: " . $_SESSION['user_id'] . "<br>";
echo "Username: " . $_SESSION['username'];
?>
Page 2 (display_session.php
):
<?php
session_start();
echo "User ID: " . $_SESSION['user_id'] . "<br>";
echo "Username: " . $_SESSION['username'];
?>
In this example, after starting the session on start_session.php
, the session data is accessible on display_session.php
without the need to reinitialize the session.
Thank you.