3 Ways to Change Default Session Time in PHP Code Examples

How to Change Default Session Time in PHP Code Snippet

The article explores how to change default session time in PHP. Here’s one example from the article.

// session shoud last for atleast one hour.
ini_set('session.gc_maxlifetime', 3600);
session_start(); // start the session!

Not sure what sessions are? Want to see other ways of increasing session expiration time in PHP? Just stay with us until the end to learn more.

PHP Default Sessions Background Context

HTTP (Hyper Text Transfer Protocol) is a protocol for communication between web browsers (clients) and web servers. A standard set of rules establishes how the two entities should communicate over the web. The following figure illustrates a typical HTTP communication between a client and a web server.

How to Change Default Session Time in PHP

The figure shows the sequence of messages passed to and from the communicating entities.

  • A user searches for a URL to access a web page.
  • The browser (client) makes an HTTP request to the web server for the required resource.
  • The web server returns the requested response with a success status code.
  • The web browser renders the page on the screen for the user.

The figure shows a general flow of HTTP communication, but there’s more than that and by diving deeper into this subject, we can learn about HTTP headers, status codes, and other complexities but let’s keep that for some other time! 

HTTP is Stateless!

HTTP is a stateless protocol. It means that a receiving entity doesn’t retain any information about the sender. Every HTTP request is independent of every other HTTP request. So, the next time you ask your server about the last interaction, it won’t remember anything. (That’s why there are sessions and cookies, more on that next)

 Still sound complicated? Let’s see this in a fun way.

stateless HTTP

Oops! Sounds rather rude. The server doesn’t remember anything about the previous interaction (request). That’s because HTTP is a stateless protocol. It might seem absurd, but this is solely for performance purposes. The protocol doesn’t overcomplicate matters by keeping information on requests. 

Just because a server doesn’t need to bother once the request/response cycle ends makes HTTP simple, secure, fast, and reliable.

But what if an application requires a server to remember information? For instance, a social media application? It would be practically impossible to build such an application. There is a way out: Sessions, which we will cover next. 

What is Session?

A session is a set of user interactions with a user in a timeframe. You initiate a session with the social media web server when you log in to your social media account. So, the web server retains information about you as long as you’re logged in. 

Let’s revisit the last image example and see the session in action.

How to change default session time in PHP

Perfect! The server now remembers the user. Observe that the user sends a session ID. That’s where the magic happens. A session ID is a unique identifier of a user. The server uses this identifier to retrieve the data of the user. 

Depending on the implementation, the server usually stores the data in cache or main memory. The identifier helps the server fetch the user’s data, and that’s how it never loses track of its users. 

Problem solved. But wait! Have you heard about cookies? They are somewhat for the same purpose. Let’s see how.

What are Cookies?

Cookies are the information servers send over to the client, and the client persists that data in its local storage. The information is passed on to the server when the client interacts with it, and that’s how the server can keep track of a user.

Cookies come in different flavors, but we won’t get into that. One important thing to remember is that cookies get stored in local storage and could be vulnerable to data theft. Besides, they are editable and susceptible to unwanted modifications.

That’s why the session ID mechanism overtakes cookies in that aspect. Some sites may use cookies, but for more non-critical user information, for instance, a user’s favorite theme.

What is Session Timeout?

A session doesn’t last forever because if it does so, it may compromise security and privacy. A never ending session may open doors to someone else assuming your identity by hijacking an open session. That’s why a session expires after a specific time or period of inactivity.

session expire dialog box

What is the Default Session Timeout in PHP?

The session time duration is defined in the php.ini configuration file. Typically the default time is 24 minutes (1440 seconds). Some web hosts may alter this configuration.

So, how do you change the default session time in PHP?

Changing the Default Session Time in PHP

Let’s explore a couple of options to learn how to increase session timeout in PHP.

Option 1: Change the Default Session Time in PHP in the php.ini File

The php.ini keeps the PHP server configuration. The session.gc_maxlifetime is the one we need out of all configuration options. It specifies the number of seconds before the session expires, and the data is garbage collected. 

This change is going to be easy. All you need is to follow the following steps.

  1. Navigate to the php.ini file. (Usually in the PHP root folder).
  2. Find session.gc_maxlifetime.
  3. Change the assigned value to the value of your choice.
How to Change Default Session Time in PHP

In the screenshot above, we have assigned 3600 seconds (1 hour) to the session.gc_maxlifetime, and that’s how to set default session timeout in PHP.

Change the Default Session Time in PHP Dynamically using ini_set

There’s also a way to increase the timeout in PHP on the go right before starting a session in the script. The following code snippet demonstrates that.

// session shoud last for atleast one hour.
ini_set('session.gc_maxlifetime', 3600);
session_start(); // start the session!

Voila! The ini_set function in PHP sets the value of a configuration option right at the time of executing the script.

Changing PHP Default Session Time by Updating the $_SESSION Global Array

There’s another way to programmatically start a session, set a timeout, and destroy it as soon as it expires. This option doesn’t modify any configuration options. Here’s how.

Updating Default Session Time in PHP Code Script through Global Array

$current = time();
if(isset($_SESSION["session_time"]) && $current > $_SESSION["session_time"]) {
    //The session has expired.
    session_unset(); //Unset session data
    session_destroy(); //Close the expired session
    session_start(); //Starts a new session
$_SESSION["session_time"] = $current + 3600; //Expires after one hour from the current time.

The example destroys a session if it is expired. The example uses session functions in PHP. $_SESSION is a global associative array in PHP. It keeps session data available throughout the PHP application.

Phew! That was a lot. Let’s jump to our conclusion on PHP session timeouts.

Changing the Default PHP Session Timeout

This article explores how to set default session timeout in PHP. Before jumping into specifics, the article explains the HTTP protocol, a stateless protocol for communication between a client and a web server. It features introductory sections of sessions and cookies and how they are important in a stateless protocol like HTTP.

After all the basic stuff, the article explores three different options for how to change the default session time in PHP.So, that’s all for this article. Stay tuned at FuelingPHP to learn more.

Related Classes & Functions to Default Session Time in PHP

Ini_set: (PHP 4, 5, 7, 8) A core PHP function that sets the configuration options. It has been there from PHP 4, made its way upto PHP 8, and seems stable enough to remain useful in the future.

session_start: (PHP 4, 5, 7, 8) A PHP function for starting or resuming an existing session. It is available in all versions of PHP and will remain available in the future.

session_destroy: (PHP 4, 5, 7 ,8)  This core PHP function destroys all the data associated with a session. Available since PHP 4 and remains stable throughout. There seems to be no chance of depreciation shortly.

session_unset: (PHP 4, 5, 7, 8)  This function free up all the session variables. This function has been used since PHP 4 and is available in the latest PHP. Given its utility and stability, it would stay in future versions.

Learn more about PHP

We have many fun articles related to PHP. You can explore these to learn more about PHP.

Article Categories

Article Tags

© 2022 Confident.Systems