How to set the lifetime of cookies. How are cookies different from a session in PHP? How to find out the session lifetime

The period of operation of the PHP $_SESSION variables, and as a consequence, the activity of web applications, depends on the duration of the session. For example, if a user is logged into the system, the time during which he can be inactive without having to re-enter his login and password depends on this parameter.

Exist different ways Setting the session lifetime. Let's try to figure it out with an example operating system Linux.

How to find out the session lifetime

Before setting up, it is worth looking at the current state. There are several methods to do this:

1. On the server using the php command

php -i | grep session

We get a list of parameters related to sessions. We are interested in:

  • session.cookie_lifetime => 0 => 0
  • session.gc_maxlifetime => 1440 => 1440

These values ​​are the default value. cookie_lifetime => 0 tells about the effect of cookies until the browser is closed if you set this parameter specific value, the session will be interrupted when there is an active session, so it is better to leave it at zero.

2. Using the php function ini_get

$maxlifetime = ini_get("session.gc_maxlifetime");
$cookielifetime = ini_get("session.cookie_lifetime");

Echo $maxlifetime;
echo $cookielifetime;

systemctl restart apache2 || systemctl restart httpd

* in Linux versions without systemd we use the command service apache2 restart or service httpd restart.

If we use FastCGI (PHP-FPM):

Configuration via .htaccess file

This file allows the webmaster to manage some web server settings. To edit it you need access to the site files. The method will not work if the PHP handler is not Apache, but, for example, NGINX + PHP-FPM. Although, there is also a way (more on it below).

We add the following to the .htaccess file:

php_value session.gc_maxlifetime 86400
php_value session.cookie_lifetime 0

* as you can see, the parameters are the same as when configured via php.ini.

As mentioned above, the method will not work if Apache is not used. However, the setup can be done on the server (again, we must have the appropriate access).

Open the web server configuration file, for example, in php-fpm:

vi /etc/php-fpm.d/www.conf

and edit/add:

php_value = 86400
php_value = 0

Then we restart the service:

systemctl restart php-fpm || service php-fpm restart

Setting a parameter in application code

The method may be useful when different pages portals must have different session lifetimes. To do this, you can use the PHP functions ini_set and session_set_cookie_params, for example:

Ini_set("session.gc_maxlifetime", 86400);
ini_set("session.cookie_lifetime", 0);
session_set_cookie_params(0);

Session_start();

Functions must be called before opening a session (session_start).

Setting up a session in the application

Some applications may override settings. In this case, you need to set the session lifetime in the program parameters. Each application has its own settings, which you need to figure out yourself. Let's take an example of setting up a session in the Bitrix CMS.

Let's go to Group of users- select a group - Safety. Find the parameter “Session lifetime (minutes)” and set the time, for example 1440 (24 hours in minutes).

How to automatically renew sessions

If the session is issued for a certain period and ends on certain time, this may cause the user's active session to be interrupted. It is much more convenient if the session duration is automatically extended if the visitor refreshes the page. For this, there is the cookie_lifetime parameter, which in all the examples above we set to 0.

If we set the cookie_lifetime value to 86400, then the session will be terminated after 24 hours. This is not always convenient.

If there is a need to control and interrupt the session, you can use the PHP function session_destroy().

Session file storage path

The storage location for session files is specified by the parameter session.save_path also, so is the time of life. By default, the path can be used /var/lib/php/sessions.

This is an important parameter - if the web server does not have write permissions to this directory, this will lead to the inability to store sessions, which will cause unexpected results from applications.

Cookies are a browser's data storage mechanism. remote computer to identify returning visitors and store web page parameters (for example, variables).

Let's give an example of using Cookies using a specific example.

Let's say we need to write a website visit counter. We need to know how many visits to the site were made by each specific visitor.

This problem can be solved in two ways. The first one is to keep a record of users' IP addresses. To do this, you need a database of just one table, the approximate structure of which is as follows:

When a user visits a site, we need to determine his IP address, find information about his visits in the database, increase the counter and display it in the visitor's browser. It is not difficult to write a handler (script) for such a procedure. However, when using this method we have the following problems:

  • For each IP address, you need to keep records in one table, which can be very large. And it follows from this that we are using processor time and disk space irrationally;
  • Most home users have dynamic IP addresses. That is, today his address is 212.218.78.124, and tomorrow - 212.218.78.137. Thus, there is a high probability of identifying one user several times.

You can use the second method, which is much easier to implement and more effective. We set a variable in the Cookie that will be stored on the remote user's disk. This variable will store information about visits. It will be read by the script when the visitor accesses the server. The benefits of this identification method are obvious. First, we don't need to store a lot of unnecessary information about IP addresses. Secondly, we are not interested in dynamic IP addresses, since data about their visits is stored specifically for each site visitor.

Now it’s clear why we can use Cookies - to store a small amount of information from the client (visitor) of the site, for example: site settings (page background color, language, table design, etc.), as well as other information.

Cookies are ordinary text files that are stored on the disk of website visitors. Cookies files contain the information that was recorded in them by the server.

Programming Cookies

Let's start programming Cookies.

To set Cookies, use the function SetCookie(). There are six parameters you can specify for this function, one of which is required:

  • name - specifies the name (of strings) assigned to the Cookie;
  • value - defines the value of the variable (string);
  • expire - variable lifetime (integer). If this parameter is not specified, the Cookie will “live” until the end of the session, that is, until the browser is closed. If a time is specified, then when it arrives, the Cookie will self-destruct.
  • path - path to Cookie (string);
  • domain - domain (string). The value is set to the name of the host from which the Cookie was installed;
  • secure - Cookie transmission via a secure HTTPS connection.

Usually only the first three parameters are used.

Example of setting Cookies:



SetCookie("Test" , "Value" );

// Set Cookie for one hour after installation:
SetCookie("My_Cookie", "Value", time()+ 3600);

?>

When using Cookies, please be aware that Cookies must be set before the first output of information to the browser (for example, by the echo operator or the output of any function). Therefore, it is advisable to set Cookies at the very beginning of the script. Cookies are set using a specific server header, and if the script outputs anything, it means the body of the document begins. As a result, Cookies will not be installed and a warning may be displayed. To check whether Cookies were installed successfully, you can use the following method:

// Set Cookie until the end of the session:
// If the Cookie is successfully set, the SetCookie function returns TRUE:
"

Cookies have been successfully installed!

" ;
?>

Function SetCookie() returns TRUE if the Cookie was successfully set. If the Cookie cannot be set, SetCookie() will return FALSE and possibly a warning (depending on PHP settings). Example of unsuccessful Cookie installation:

// Cookies cannot be set because before sending
// Cookie header we display the string "Hello" to the browser:
echo "Hello" ;
// The SetCookie function will return FALSE:
if (SetCookie("Test" , "Value" )) echo "

Cookie set successfully!

" ;
else echo "

Cookie could not be set!

"
;
// Prints "Cookie could not be installed!".
?>

The cookie could not be set because we printed the string "Hello" to the browser before sending the Cookie header.

Reading Cookies Values

Accessing Cookies and their values ​​is quite simple. They are stored in the superglobal arrays $_COOKIE and $HTTP_COOKIE_VARS .

The values ​​are accessed by the name of the installed Cookies, for example:

echo $_COOKIE["my_cookie"];
// Displays the values ​​of the installed Cookie "My_Cookie"

An example of setting a Cookie and then reading it:

// Set Cookie "test" with the value "Hello" for one hour:
setcookie ("test" , "Hello" , time ()+ 3600 );
// The next script request prints "Hello":
echo @$_COOKIE [ "test" ];
?>

In the example considered, the first time the script is accessed, the Cookie "test" is set with the value "hello". When you access the script again, the Cookie value "test" will be displayed, that is, the string "Hello".

When reading Cookies values, pay attention to checking for the existence of Cookies, for example using the operator isset(). Either by suppressing error output by the operator @

Here is an example of how to build a counter for the number of page loads using Cookies:

// Check if the "Mortal" Cookie has already been set,
// If yes, then read its value,
// And increase the value of the page access counter:
if (isset ($ _COOKIE [ "Mortal" ])) $ cnt = $ _COOKIE [ "Mortal" ]+ 1 ;
else $cnt = 0 ;
// Set Cookie "Mortal" with the counter value,
// With "life" time up to 07/18/29,
// That is, for a very long time:
setcookie ("Mortal" , $ cnt , 0x6FFFFFFF );
// Displays the number of visits (downloads) of this page:
echo "

Have you visited this page " .@$_COOKIE ["Mortal" ]. " once

" ;
?>

Removing Cookies

Sometimes it becomes necessary to delete Cookies. This is not difficult to do; you just need to set the Cookie again with an identical name and an empty parameter. For example:

//Delete Cookie "Test":
SetCookie("Test" , "" );
?>

Setting the Cookies array and his reading

We can set the Cookies array using square brackets in the Cookies names, and then read the Cookies array and the values ​​of that array:

// Set up the Cookies array:
setcookie ("cookie" , "First" );
setcookie ("cookie" , "Second" );
setcookie("cookie", "Third");

// After the page reloads we will display
// Composition of the Cookies array "cookie":
if (isset ($ _COOKIE [ "cookie" ])) (
foreach ($_COOKIE["cookie"] as $name => $value) (
echo "$name: $value
" ;
}
}
?>

The benefits of using Cookies are undeniable. However, there are also some problems with their use. The first of these is that the visitor can block the reception Cookies by browser or simply delete all or part of the Cookies. Therefore, we may have some difficulty identifying such visitors.



<<< Назад Content Forward >>>
If you have any other questions or something is not clear - welcome to our

Well, let's figure it out.

First, read about HTTP on the same wiki. You don’t need to know it thoroughly, but you should have a minimal understanding of the request/response structure, understand that the request and response have headers and a body (there may not be a body, depending on the type of request/response).

So here it is. Cookies. Cookies live on the browser side. They are transmitted in the HTTP header for every request to the server (even if you went to get the pictures). There are just cookies, there are http-only cookies. Cookies can be separated by host and path. All this gives us flexibility and helps with security. In PHP, the contents of $_COOKIE are provided to us by SAPI. When PHP receives a request for processing, the SAPI used (php-fpm, cgi, mod_php have their own SAPI implementations) this moment takes the request headers and body, parses them and fills all these super-global arrays like $_SERVER, $_GET, including $_COOKIE. Everything that the client sent us (something that makes requests is the client, something that processes them is the server), and the browser sends us cookies only those that are possible based on where the request is sent. Cookies are set using the Set-Cookie header in the response, that is, here you need to read more about HTTP and not about PHP. PHP just lets you work with this stuff. You can set cookies directly by working with response headers using the header function. Moreover, if you set the lifetime of cookies to 0, then they, and not the session, will be reset when the browser is closed, since it will forget all such cookies.

Here... sessions... In PHP, a session is usually a file. Just some file with a random name. If, say, session.autostart is specified in php.ini or a session_start call is made, then a file is created for the user session (you can move it to Radish or Memcache, your storage, etc., depending on your needs. The data can also be encrypted, which is what happens by default ). This file has an ID, just some random string. And if, when processing a request, a session from the previous request was not found, a new one is created.

And now we come to the most interesting thing - how PHP connects the session from the previous request with the current one. And here everything is quite simple - cookies. When a user is assigned a session, an http-only cookie is automatically set (so that bad people can’t steal our session from js) in which the session identifier is written. In the browser debugger, you can see if you have a PHPSESSID cookie (the name can be changed in the settings, and in general, sessions can be linked not only through cookies, but these are already security issues) when you experiment with sessions.

When a request is processed by SAPI, if session.autostart is present, before starting to create a new session, puff still looks to see if we have a cookie with a session identifier, checks whether it has one, and if it does, it calms down and does not create a new one. Since the session is bound through cookies, you can set the lifetime of this cookie itself (in php.ini) and thus regulate the lifetime of the session.

Here... when to use cookies and when to use sessions? It is advisable to understand that the more data in cookies (and they have a word limit), the more data we transfer for each request. That is, it’s not cool when, in order to receive 1 kilobyte of data, we must transfer a couple of kilobytes of cookies in the headers. People who are focused on optimization even store images on separate cookie-less domains to reduce the amount of traffic and packets (usually a simple HTTP request fits into the size of one TCP packet). If you need to work with this data from JS on any page, for example, the locale selected by the user in order to apply translations in JS, then you should use cookies. For everything else, it’s better to use sessions, of course. In any case, in the initial stages, when you don’t have to do anything very complicated.

Computer