Настройка сохранения сессий php

session_save_path

session_save_path() returns the path of the current directory used to save session data.

Parameters

Session data path. If specified and not null , the path to which data is saved will be changed. session_save_path() needs to be called before session_start() for that purpose.

Note:

On some operating systems, you may want to specify a path on a filesystem that handles lots of small files efficiently. For example, on Linux, reiserfs may provide better performance than ext2fs.

Return Values

Returns the path of the current directory used for data storage, or false on failure.

Changelog

See Also

User Contributed Notes 5 notes

I made a folder next to the public html folder and placed these lines at the very first point in index.php

Location of session folder:

What I placed in index.php at line 0:

ini_set ( ‘session.save_path’ , realpath ( dirname ( $_SERVER [ ‘DOCUMENT_ROOT’ ]) . ‘/../session’ ));
session_start ();

This is the only solution that worked for me . Hope this helps someone .

Debian does not use the default garbage collector for sessions. Instead, it sets session.gc_probability to zero and it runs a cron job to clean up old session data in the default directory.

As a result, if your site sets a custom location with session_save_path() you also need to set a value for session.gc_probability, e.g.:

session_save_path ( ‘/home/example.com/sessions’ );
ini_set ( ‘session.gc_probability’ , 1 );
?>

Otherwise, old files in ‘/home/example.com/sessions’ will never get removed!

Session on clustered web servers !

We had problem in PHP session handling with 2 web server cluster. Problem was one servers session data was not available in other server.

So I made a simple configuration in both server php.ini file. Changed session.save_path default value to shared folder on both servers (/mnt/session/).

If session.save_handler is set to files, on systems that have maximum path length limitations, when the session data file’s path is too long, php may get you an error like «No such file or directory» and fails to start session, although the session-saving folder really exists on the disk.

1. Keep the session-saving folder’s absolute path not too long
2. If you’re with PHP 7.1+, don’t set session.sid_length to a number too great, such as 255

I once got stuck with this problem on Windows and wasted hours to solve it.

ini_set ( ‘session.save_path’ , realpath ( dirname ( $_SERVER [ ‘DOCUMENT_ROOT’ ]) . ‘/tmp’ ));
ini_set ( ‘session.gc_probability’ , 1 );
session_start ();

?>

(for using above code create a tmp folder/directory in your directory)

  • Session Functions
    • session_​abort
    • session_​cache_​expire
    • session_​cache_​limiter
    • session_​commit
    • session_​create_​id
    • session_​decode
    • session_​destroy
    • session_​encode
    • session_​gc
    • session_​get_​cookie_​params
    • session_​id
    • session_​module_​name
    • session_​name
    • session_​regenerate_​id
    • session_​register_​shutdown
    • session_​reset
    • session_​save_​path
    • session_​set_​cookie_​params
    • session_​set_​save_​handler
    • session_​start
    • session_​status
    • session_​unset
    • session_​write_​close

    Источник

    Настройка времени сессий в PHP

    Обновлено

    Обновлено: 08.04.2021 Опубликовано: 25.02.2018

    Тематические термины: PHP, Веб-сервер, Cookie. От времени действия сессии зависит период работоспособности PHP-переменных $_SESSION, и как следствие, активности веб-приложений. Например, если пользователь авторизовался в системе, время в течении которого он может бездействовать без необходимости повторного ввода логина и пароля зависит от данного параметра. Существуют разные способы установки времени жизни сессий. Попробуем разобраться на примере операционной системы Linux.

    Как узнать время жизни сессии

    1. На сервере командой php

    Данные значения — значение по умолчанию. cookie_lifetime => 0 говорит о действии файлов куки до закрытия браузера, если задать этому параметру определенное значение, сессия будет прерываться при активном сеансе, поэтому лучше ее оставлять в значении ноль.

    2. C помощью php-функции ini_get

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

    echo $maxlifetime;
    echo $cookielifetime;

    Настройка сессий на веб-сервере

    Выполняется путем настройки файла php.ini. Данный способ удобен, если мы являемся администратором веб-сервера, а также если есть гарантия, что общая настройка сессий не повлияет на работоспособность всех веб-приложений, работающих на данном сервере.

    Открываем на редактирование php.ini. Его расположение зависит от сборки Linux. Точный путь можно посмотреть командой:

    Теперь открываем сам файл:

    * в моем случае каманда php -i | grep php.ini вернула данный путь.

    В некоторых системах, например, Ubuntu или Debian для каждой среды обработки кода создается свой php.ini файл, а также для каждой версии PHP. Например, по пути /etc/php/7.4/fpm/php.ini находится файл для php-fpm для PHP версии 7.4. Нам необходимо учитывать данный факт, чтобы настроить нужный файл.

    И редактируем следующие параметры:

    session.gc_maxlifetime = 86400
    session.cookie_lifetime = 0

    * где параметр gc_maxlifetime указывает на временя в секундах, после прошествии которого данные могут быть удалены; cookie_lifetime — время жизни файлов cookies; 86400 — 24 часа в секундах.
    * если параметру gc_maxlifetime задать значение 0, действие сессий будет бесконечным. Это, как правило, не стоит делать — приведет к падению производительности и безопасности сервера.

    После настройки параметров, необходимо перезагрузить сервер, являющийся интерпретатором PHP.

    systemctl restart apache2 || systemctl restart httpd

    * в версиях Linux без systemd используем команду service apache2 restart или service httpd restart.

    Если используем FastCGI (PHP-FPM).

    systemctl restart php7.4-fpm

    * где 7.4 — версия используемого PHP.

    Настройка через файл .htaccess

    Данный файл позволяет веб-мастеру управлять некоторыми настройками веб-сервера. Для его редактирования нужен доступ к файлам сайта. Способ не сработает, если в качестве обработчика PHP используется не Apache, а, например, NGINX + PHP-FPM. Хотя, тут тоже есть способ (о нем будет ниже).

    В файл .htaccess вносим следующее:

    php_value session.gc_maxlifetime 86400
    php_value session.cookie_lifetime 0

    * как можно заметить, параметры те же, что при настройки через php.ini.

    Как говорилось выше, метод не сработает, если не используется Apache. Однако настройку можно выполнить на сервере (опять же, у нас должен быть соответствующий доступ).

    Открываем файл настройки веб-сервера, например, в php-fpm:

    php_value[session.gc_maxlifetime] = 86400
    php_value[session.cookie_lifetime] = 0

    После перезапускаем сервис:

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

    Задание параметра в коде приложения

    Способ может быть полезен, когда разные страницы портала должны иметь разное время жизни сессии. Для этого можно воспользоваться PHP-функциями ini_set и session_set_cookie_params, например:

    ini_set(‘session.gc_maxlifetime’, 86400);
    ini_set(‘session.cookie_lifetime’, 0);
    session_set_cookie_params(0);

    Функции обязательно вызывать до открытия сесии (session_start).

    Установка сессии в приложении

    Некоторые приложения могут переопределять настройки. В таком случае, задать время жизни сессии необходимо в параметрах программы. У каждого приложения свои настройки, в которых необходимо самостоятельно разобраться. Приведем для примера настройку сессии в CMS Битрикс.

    Заходим в Группы пользователей — выбираем группу — Безопасность. Находим параметр «Время жизни сессии (минут)» и ставим время, например 1440 (24 часа в минутах).

    Как автоматически продлевать сессии

    Если сессия выдается на определенный период и заканчивается в определенное время, это может привести к прерыванию активного сеанса пользователя. Гораздо удобнее, если время действия сессии будет автоматически продлеваться, если посетитель обновляет страницу. Для этого существует параметр cookie_lifetime, который во всех примерах выше мы задавали в значении 0.

    Если мы зададим значение cookie_lifetime 86400, то через 24 часа сессия прервется. Это не всегда удобно.

    Если есть необходимость в контроле и прерывании сессии, можно воспользоваться php-функцией session_destroy().

    Путь хранения файлов сессий

    Место хранения файлов сессий задается параметром session.save_path также, так время жизни. По умолчанию, может использоваться путь /var/lib/php/sessions.

    Это важный параметр — если у веб-сервера будут отсутствовать права на запись в данный каталог, это приведет к невозможности хранить сессии, что вызовет неожиданные результаты работы приложений.

    Источник

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

    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:

    which was used to make sure that all automatically generated links had the right prefix (just like $cfg[‘PmaAbsoluteUri’] works in phpMyAdmin). After introducing that variable, no link would pass the SID anymore, causing every script to return to the login page. It took me hours (!!) to recognize that this wasn’t a bug in my code or some misconfiguration in php.ini and then still some more time to find out what it was. The above restriction had completely slipped from my mind (if it ever was there. )

    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:

    if( version_compare ( phpversion (), ‘4.3.0’ )>= 0 ) <
    if(! ereg ( ‘^SESS2+$’ , $_REQUEST [ ‘SESSION_NAME’ ])) <
    $_REQUEST [ ‘SESSION_NAME’ ]= ‘SESS’ . uniqid ( » );
    >
    output_add_rewrite_var ( ‘SESSION_NAME’ , $_REQUEST [ ‘SESSION_NAME’ ]);
    session_name ( $_REQUEST [ ‘SESSION_NAME’ ]);
    >
    ?>

    How it works:

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

    After we check if the SESSION_NAME element in $_REQUEST array is a valid string in the format «SESSIONxxxxx», where xxxxx is an unique id, generated by the script. If SESSION_NAME is not valid (ie. not set yet), we set a value to it.

    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.

    Источник

    Читайте также:  Text html чем открыть
Оцените статью