php session cache expire

Работа с сессиями в PHP

Отредактировано: 04 Февраля 2019

Сессия, механизм php, созданный для возможности передачи данных предназначенных конкретному пользователю при повторных запросах (веб-сервер не поддерживает постоянного соединения с клиентом, и каждый запрос обрабатывается, как новый, без какой-либо связи с предыдущими).

Принцип работы сессий: сервер выдает браузеру уникальный идентификатор, и просит передавать его с каждым запросом. Передача происходит стандартными способами, либо через куки, либо через переменные POST/GET.

Идентификатор сессии — это обычная переменная, по умолчанию ее имя — PHPSESSID. Можно изменить директивой session.name в php.ini.

На сервере за передачу информации о сессиях отвечают две настройки в php.ini:

Соответственно, если включена только первая настройка и браузер отдает куки, то идентификатор передается через них, если не отдает, то сессия обнуляется при каждом запросе.

Если включена только вторая, то PHP дописывает к каждой относительной ссылке и к каждой форме передачу идентификатора сессии, примерно так:

Если включены обе, то браузеру выставляется кука, а ссылки и формы дополняются только если кука найдена не была.

Запись данных в сессию работает так:

Используем например так:

Удаление переменных из сессии:

Для закрытия сессии используется функция:

Для управления HTTP-заголовками отвечающими за кэш, используется функция session_cache_limiter(). Установка nocache, например, отменяет кэширование на стороне клиента.

Источник

Функции для работы с сессиями

Содержание

User Contributed Notes 23 notes

# write and close current session
session_write_close ();

Be aware of the fact that absolute URLs are NOT automatically rewritten to contain the SID.

Of course, it says so in the documentation (‘Passing the Session Id’) and of course it makes perfectly sense to have that restriction, but here’s what happened to me:
I have been using sessions for quite a while without problems. When I used a global configuration file to be included in all my scripts, it contained a line like this:

Skipping the ‘http:’ did the job.

OK, it was my own mistake, of course, but it just shows you how easily one can sabotage his own work for hours. Just don’t do it 😉

Sessions and browser’s tabs

May you have noticed when you open your website in two or more tabs in Firefox, Opera, IE 7.0 or use ‘Control+N’ in IE 6.0 to open a new window, it is using the same cookie or is passing the same session id, so the another tab is just a copy of the previous tab. What you do in one will affect the another and vice-versa. Even if you open Firefox again, it will use the same cookie of the previous session. But that is not what you need mostly of time, specially when you want to copy information from one place to another in your web application. This occurs because the default session name is «PHPSESSID» and all tabs will use it. There is a workaround and it rely only on changing the session’s name.

Put these lines in the top of your main script (the script that call the subscripts) or on top of each script you have:

First we compare if the PHP version is at least 4.3.0 (the function output_add_rewrite_var() is not available before this release).

uniqid(») will generate an unique id for a new session name. It don’t need to be too strong like uniqid(rand(),TRUE), because all security rely in the session id, not in the session name. We only need here a different id for each session we open. Even getmypid() is enough to be used for this, but I don’t know if this may post a treat to the web server. I don’t think so.

output_add_rewrite_var() will add automatically a pair of ‘SESSION_NAME=SESSxxxxx’ to each link and web form in your website. But to work properly, you will need to add it manually to any header(‘location’) and Javascript code you have, like this:

The last function, session_name() will define the name of the actual session that the script will use.

So, every link, form, header() and Javascript code will forward the SESSION_NAME value to the next script and it will know which is the session it must use. If none is given, it will generate a new one (and so, create a new session to a new tab).

May you are asking why not use a cookie to pass the SESSION_NAME along with the session id instead. Well, the problem with cookie is that all tabs will share the same cookie to do it, and the sessions will mix anyway. Cookies will work partially if you set them in different paths and each cookie will be available in their own directories. But this will not make sessions in each tab completly separated from each other. Passing the session name through URL via GET and POST is the best way, I think.

Источник

session_cache_limiter

(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)

session_cache_limiter — Получить и/или установить текущий режим кеширования

Описание

session_cache_limiter() возвращает имя текущего режима кеширования.

Режим кеширования определяет, какие HTTP-заголовки управления кешем посылать клиенту. Эти заголовки определяют, какими правилами кеширования контента должны руководствоваться клиент и промежуточные прокси. Установка ограничителя в значение nocache запрещает любое кеширование. Значение public разрешает кеширование как на стороне клиента, так и на прокси-серверах. private запрещает кеширование прокси-серверам, но разрешает клиенту.

Установка режима кеширования в » отключает автоматическую отправку кеш-заголовков.

Во время начала запроса режим кеширования сбрасывается до значения по умолчанию, хранящегося в session.cache_limiter. Таким образом, вам необходимо вызывать session_cache_limiter() для каждого запроса (перед тем, как вызвана функция session_start() ).

Список параметров

Возможные значения

Возвращаемые значения

Список изменений

Примеры

Пример #1 Пример использования session_cache_limiter()

/* установить режим кеширования на ‘private’ */

session_cache_limiter ( ‘private’ );
$cache_limiter = session_cache_limiter ();

Смотрите также

User Contributed Notes 25 notes

The actual headers that are set using the values described above are:

public:
Expires: pageload + 3 hours
Cache-Control: public, max-age=10800

private:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: private, max-age=10800, pre-check=10800

nocache:
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

private_no_expire:
Cache-Control: private, max-age=10800, pre-check=10800

I have had some trouble preventing IE, particular IE 7 to stop caching pages. I read quite a number of articles relating to people’s experiences and how they fixed it but it was hard to find one that worked for me. Eventually I had to use the following fix:

based on the information available on following url: http://support.microsoft.com/kb/234067

Would to God that we’d all quit IE for good. Hope this saves someone some agony over IE.

You can find more information about to control the cache in PHP at http://www.php.net/manual/en/function.header.php

If you have a dinamic website and want to allow your visitors to use the back button after they sent a form with the post method, the best combination I found was:

// and after you start the session
session_start ();

?>

I try some combinations using header(«Cache-Control: no-cache, must-revalidate»), but when clicking the back button, the last changes in the form back to their previous states. The combination above works fine with IE 6.x. I didn’t test this with other browsers.

When I try something like session_cache_limiter(«nocache, must-revalidate») it doesn’t work. The page only updates when I used the browser’s refresh button. In dynamic web sites this is not good. The content must be fresh after each click.

I didn’t find these combinations like «private, must-revalidate» documented in the manual and I guess that something different from «none, nocache, private, public and private_no_expire» are resolved to «none» or something like that. One thing I notice is that in session_cache_limiter() it is «nocache», but in header() it is «no-cache». This may give us some clues about how session_cache_limiter() function works.

About caching, the perfect solution I think is to give the correct expiration date and time and also the right last-modified header for each element in the web site, when they are really updated. This means a lot of extra controls of course, but may worth in web sites with high overload.

The «public» option means that all available cache in proxies and clientes will be used, so this improves the speed of the web site and also reduces the used bandwidth. But without the right expiration and last-modified headers, you can use it only in static web sites.

The «private» option means that only the cache in clients will be used. This is good for a more sensitive data that can be stored locally in the browser cache. It have some benefits of the public option, but the same restrictions too.

The «nocache» (or no-cache?) option means that the HTML portion will not be cached, but the images, CSS and JS files will. This is good for dynamic websites because you still can use the power of cache without loose the refreshness after each click. These files can be updated when you open the web site or use the browser’s refresh button.
I don’t know why, but flash files are never updated when you click the refresh button. A common solution for this is to change the file name when you update the flash file.

The «no-store» option means that all the content will not be cached anyway, including images, CSS or JS files. I don’t know if this applyes to flash files too, but is possible. This option must be used with very sensitive data. I think the SSL uses this by default.

I have PHP 4.3 running on a Windows 2003 Server running IIS 6.0 also using SSL encryption for my pages. I could not (for the life of me) figure out how to get IE 6.0/WinXPPro to recognize a set of HTML tables as an Excel spreadsheet export, and it was due to the header() variables I was using. Hopefully these are helpful to others who are attempting the same type of export within PHP.

*This example builds on the previously submitted one, adding a few necessary headers.

session_cache_limiter ( «must-revalidate» );
header ( «Content-Type: application/vnd.ms-excel» );
header ( ‘Content-Disposition: attachment; filename=»fileToExport.xls»‘ );

// and after you start the session
session_start ();
?>

I had a problem using a FORM with POST method when user of my website was using the back button. The page requested a refresh to be able to see again the FORM.

To solve the problem I used :
( ‘private, must-revalidate’ );
?>

*You need to write this line before any output

Источник

How do I expire a PHP session after 30 minutes?

I need to keep a session alive for 30 minutes and then destroy it.

17 Answers 17

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I’ll explain the reasons for that.

First:

session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP’s default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file’s last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won’t have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

And second:

session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

Yes, that’s right. This only affects the cookie lifetime and the session itself may still be valid. But it’s the server’s task to invalidate a session, not the client. So this doesn’t help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

Updating the session data with every request also changes the session file’s modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

Источник

session_cache_expire

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

session_cache_expire — Получает и/или устанавливает срок действия текущего кеша

Описание

Срок действия сбрасывается до значения по умолчанию (180), хранящегося в session.cache_expire во время запроса. Таким образом, нужно вызывать session_cache_expire() для каждого запроса (и до вызова session_start() ).

Список параметров

Возвращаемые значения

Список изменений

Примеры

Пример #1 Пример использования session_cache_expire()

/* установить ограничитель кеша на ‘private’ */

session_cache_limiter ( ‘private’ );
$cache_limiter = session_cache_limiter ();

/* установить время жизни на 30 минут */
session_cache_expire ( 30 );
$cache_expire = session_cache_expire ();

Смотрите также

User Contributed Notes 3 notes

The manual probably doesn’t stress this enough:

** This has nothing to do with lifetime of a session **

Whatever you set this setting to, it won’t change how long sessions live on your server.

This only changes HTTP cache expiration time (Expires: and Cache-Control: max-age headers), which advise browser for how long it can keep pages cached in user’s cache without having to reload them from the server.

I’ve encountered the same problem of loosing focus when using IE and a javascript window.location.refresh/replace().

After fusing around I found that a works without move the focus on the parent frame’s form. The down side is loading up the browser history and an annoying ‘click’ in IE on the page load.

Just to make things clear. If session.cache_limiter is set to private the following header will be sent in HTTP response:

Cache-Control private, max-age=10800, pre-check=10800

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

ЗначениеПосылаемый заголовок
public