logo CBCE Skill INDIA

Welcome to CBCE Skill INDIA. An ISO 9001:2015 Certified Autonomous Body | Best Quality Computer and Skills Training Provider Organization. Established Under Indian Trust Act 1882, Govt. of India. Identity No. - IV-190200628, and registered under NITI Aayog Govt. of India. Identity No. - WB/2023/0344555. Also registered under Ministry of Micro, Small & Medium Enterprises - MSME (Govt. of India). Registration Number - UDYAM-WB-06-0031863

Start a Session in PHP!


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:

  1. The session_start() function initiates or resumes a session. It should be called before accessing or modifying any session variables.

  2. 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.

Popular Post:

Give us your feedback!

Your email address will not be published. Required fields are marked *
0 Comments Write Comment