You are on page 1of 4

PHP Session

Session is a mechanism in PHP that allows us to store data on the server and access it across
multiple pages of a website. When a session is started, a unique session ID is generated and sent
to the user's browser as a cookie. This session ID is used to identify the user's session on
subsequent requests.

What is a session?
In general, session refers to a frame of communication between two medium. A PHP session is used
to store data on a server rather than the computer of the user. Session identifiers or SID is a unique
number which is used to identify every user in a session based environment. The SID is used to link
the user with his information on the server like posts, emails etc.

How are sessions better than cookies?


Although cookies are also used for storing user related data, they have serious security issues
because cookies are stored on the user’s computer and thus they are open to attackers to easily
modify the content of the cookie. Addition of harmful data by the attackers in the cookie may result
in the breakdown of the application.
Apart from that cookies affect the performance of a site since cookies send the user data each time
the user views a page. Every time the browser requests a URL to the server, all the cookie data for
that website is automatically sent to the server within the request

Automatically Start a Session


If there’s a need to use sessions throughout your application, you can also opt in to starting a session
automatically without using the session_start function.

There’s a configuration option in the php.ini file which allows you to start a session automatically
for every request—session.auto_start. By default, it’s set to 0, and you can set it to 1 to enable the
auto startup functionality.

session.auto_start = 1
On the other hand, if you don’t have access to the php.ini file, and you're using the Apache web
server, you could also set this variable using the .htaccess file.

php_value session.auto_start 1
If you add the above line in the .htaccess file, that should start a session automatically in your PHP
application.

<?php
// Start a session
session_start();

// Set a session variable


$_SESSION['username'] = 'John';

// Retrieve the session variable


$username = $_SESSION['username'];

// Print the value of the session variable


echo "Welcome, " . $username . "!<br>";

// Check if a session variable is set


if (isset($_SESSION['username'])) {
echo "The session variable 'username' is set.<br>";
} else {
echo "The session variable 'username' is not set.<br>";
}

// Get the session ID


$session_id = session_id();
echo "Session ID: " . $session_id . "<br>";

// Get the session name


$session_name = session_name();
echo "Session name: " . $session_name . "<br>";

// Set the session cookie parameters


session_set_cookie_params(3600); // Expires after 1 hour
echo "Session cookie parameters set.<br>";

// Get the session status


$session_status = session_status();
switch ($session_status) {
case PHP_SESSION_DISABLED:
echo "Sessions are disabled.<br>";
break;
case PHP_SESSION_NONE:
echo "Sessions are enabled, but no session exists.<br>";
break;
case PHP_SESSION_ACTIVE:
echo "Sessions are enabled, and a session exists.<br>";
break;
}

// Destroy the session


session_destroy();
echo "Session destroyed.<br>";
?>

In this example, we start a session using the session_start() function. This creates a unique session
ID for the user and enables us to store data across multiple pages of the website.

We then set a session variable called $_SESSION['username'] and give it a value of 'John'. This
variable can be accessed and modified from any page that has access to the same session.

Next, we retrieve the value of the session variable and store it in a local variable called $username.
We then print a welcome message to the user that includes the value of the session variable.

We also use the following session-related methods, functions, and events:

isset($_SESSION['username']): Checks if a session variable is set.


session_id(): Gets the current session ID.
session_name(): Gets the name of the current session.
session_set_cookie_params(3600): Sets the parameters for the session cookie. In this case, the
cookie will expire after 1 hour.
session_status(): Gets the current status of the session. This can be one of three values:
PHP_SESSION_DISABLED, PHP_SESSION_NONE, or PHP_SESSION_ACTIVE.
session_destroy(): Destroys the current session and all session data.
These methods, functions, and events can be used to manage sessions in PHP applications, such as
setting session variables, checking if a session variable is set, getting the session ID and name,
setting session cookie parameters, getting the session status, and destroying the session.

Storing and Retrieving Session Variables

<?php
// Start the session
session_start();

// Set session variables


$_SESSION["username"] = "John";
$_SESSION["email"] = "john@example.com";

// Retrieve session variables


echo "Username is " . $_SESSION["username"] . "<br>";
echo "Email is " . $_SESSION["email"] . "<br>";

// End the session


session_destroy();
?>

In this example, we start the session using the session_start() function. We then set two session
variables, "username" and "email", with the values "John" and "johndoe@example.com",
respectively. We retrieve these variables using the $_SESSION superglobal array and print them to
the screen. Finally, we end the session using the session_destroy() function.

Work with session IDs and session variables:


How to Get a Session Id
As we discussed earlier, the server creates a unique number for every new session. If you want to
get a session id, you can use the session_id function, as shown in the following snippet.

<?php
session_start();
echo session_id();
?>
That should give you the current session id. The session_id function is interesting in that it can also
take one argument—a session id. If you want to replace the system-generated session id with your
own, you can supply it to the first argument of the session_id function.

<?php
session_id(YOUR_SESSION_ID);
session_start();
?>
It’s important to note that the session_id function must be placed before the session_start call when
you want to start a session with a custom session id.
<?php
// Start the session
session_start();

// Print the session ID


echo "Session ID: " . session_id() . "<br>";

// Set a session variable


$_SESSION["username"] = "John";

// Print the session variable


echo "Username: " . $_SESSION["username"] . "<br>";

// Destroy the session


session_destroy();
?>

we start the session using the session_start() function. We print the session ID using the session_id()
function, which returns the current session ID. We then set a session variable called "username"
with the value "John" using the $_SESSION superglobal array. We print the value of this session
variable using the $_SESSION superglobal array as well. Finally, we destroy the session using the
session_destroy() function, which clears all session data and ends the session.

The session_destroy function deletes everything that’s stored in the current ses sion. Having said
that, it doesn't unset global variables associated with the session or unset the session cookie.

O/P
Session ID: abc123def456
Username: John

Note that the session ID may be different each time you run the script, since it is generated randomly
by PHP.By using session IDs and session variables, we can store data that persists across multiple
page loads or even across multiple sessions (i.e. when the user closes and reopens their browser).
This can be useful for implementing features like user authentication, shopping carts, and more.

PHP script that counts page views using a session:


<?php
// start a new session or resume an existing one
session_start();

// check if the "pageviews" session variable is set


if(isset($_SESSION['pageviews'])) {
// if it is, increment its value
$_SESSION['pageviews']++;
} else {
// if it is not, set it to 1
$_SESSION['pageviews'] = 1;
}

// display the number of page views


echo 'You have visited this page ' . $_SESSION['pageviews'] . ' times.';
?>

You might also like