Php session data directory

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 ();

Читайте также:  Press button selenium python

?>

(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

    Источник

    How to use Session Save Path in PHP

    session_save_path() sets or returns the path where data for the current session is saved.If you pass no arguments into a function, it returns the current directory where session files are stored.

    To Get default Session Path

    By default, PHP stores session data in files and files are stored in the /tmp directory of your server.Each session is stored in its own file.

    session data file stored in /tmp is like sess_1f1b1bdb809709f09f45b049998f25dc43745a67.

    session_save_path function returns the current session save path.If session_save_path() function returns null,then session.save_path is commented in your php.ini file.

    So Uncomment session.save_path in a php.ini and set path in it.Let’s have a look

    To Change Session Save Path

    To change the default path of stored session, you can use same function session_save_path( ) but with the parameter which is the path of the new directory where you session files will be stored but you need to call this function before accessing any session variables like session_start();

    NOTE:If sessions are not working or are giving errors, check the pathname returned by session_save_path() function and make sure that path exists and writable.

    This simple change can greatly improve the security of the sessions stored in files because we are storing it in custom directory for application so it is Securing Session Storage

    Couple of articles, you may like:

    I hope you have enjoyed this article. Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

    About Author

    Bhumi

    Bhumi shah is currently working with leading web development company as a Software Analyst and also the founder of the Creativedev. She has immense interest in programming and web designing.She is passionate about technical blogging and almost versatile in terms of programming across various languages & frameworks such as PHP,MySQL WordPress, Twitter Bootstrap, AngularJS, HTML5, CSS3, jQuery and more.

    RELATED POST

    Comments (4)

    You completed certain nice points there. I did a search on the matter and found nearly all persons will agree with your blog.

    I enjoy you because of every one of your work on this blog. My aunt really likes going through investigation and it’s really easy to understand why. Most of us learn all relating to the lively mode you deliver very important suggestions on the blog and therefore strongly encourage contribution from other individuals on the topic plus our daughter has always been being taught so much. Enjoy the remaining portion of the new year. You are always performing a dazzling job.

    I am now not positive where you are getting your information, however good topic.
    I needs to spend some time finding out more
    or figuring out more. Thank you for excellent information I used to
    be on the lookout for this info for my mission.

    Leave a Reply Cancel reply

    This site uses Akismet to reduce spam. Learn how your comment data is processed.

    Источник

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

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

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

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

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

    • session.use_cookies — если равно 1, то PHP передает идентификатор в куках, если 0 — то нет.
    • session.use_trans_sid — если равно 1, то PHP передает его, добавляя к URL и формам, если 0 — то нет.

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

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

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

    Вся информация о сессии храниться в глобальном массиве $_SESSION.

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

    // запускаем новую, либо возобновляем существующую сессию session_start(); // передаем в массив сессий переменную с названием test и данными Hello world $_SESSION['test']='Hello world!'; // если в качестве имени переменной хотим использовать значение переменной - // пишем без кавычек или используем двойные $var = name; $_SESSION["$var"]='Hello world!';
    // обычное условие проверки if(!$_SESSION[$var]){ echo "session variable is empty" } // можно получить id текущей сессии или ее имя session_id(); session_name(); 

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

    unset($_SESSION[$var]); // Если register_globals = on, надо добавить строку session_unregister($var); //Если надо сбросить все переменные сессии session_unset();

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

    Данные из глобального массива $_SESSION php хранит либо в файлах, путь к которым указывается в session.save_path в php.ini, либо в БД.

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

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

    Значение Посылаемый заголовок
    public Expires: (когда-нибудь в будущем, в зависимости от session.cache_expire)
    Cache-Control: public, max-age=(когда-нибудь в будущем, в зависимости от session.cache_expire)
    Last-Modified: (временная метка последнего сохранения сессии)
    private_no_expire Cache-Control: private, max-age=(session.cache_expire в будущем), pre-check=(session.cache_expire в будущем)
    Last-Modified: (временная метка последнего сохранения сессии)
    private Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: private, max-age=(session.cache_expire в будущем), pre-check=(session.cache_expire в будущем)
    Last-Modified: (временная метка последнего сохранения сессии)
    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

    Возможные проблемы

    • Вспомогательными вещами, вроде кодирования данных и удаления старых сессий, php занимается сам, и если возникает проблема с удалением информации о них, проверьте в php.ini строку session.gc_probability. Для того чтобы php мог самостоятельно удалять файлы сессий, должно быть установлено 1.
    • Warning: open(/tmp\sess_SID, O_RDWR) failed: No such file or directory (2) in full_script_path on line number
      или
      Warning: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp))
      в этом случае надо в php.ini, в параметре session.save_path, указать правильный каталог, который существует и доступен для записи (не забудьте перезагрузить апач).
    • Warning: Cannot send session cookie — headers already sent.
      Warning: Cannot send session cache limiter — headers already sent.
      Warning: Cannot add header information — headers already sent.
      эти ошибки возникают в том случае, если браузер ранее уже получил заголовки для страницы. Функции header(), session_start(), setcookie() и вся логика, которая их вызывает, должны обрабатываться до любого вывода в браузер.
    • Если давать переменным скрипта имена, совпадающие с индексами массива $_SESSION, возможны проблемы. При register_globals=on значения будут перезаписывать друг друга. При register_globals=off, в случае, если в скрипте есть переменная сессии не имеющая значения, и глобальная переменная с тем же именем, появится ошибка «Your script possibly relies on a session side-effect which existed until PHP 4.2.3.». Для предотвращения этой ошибки, надо инициализировать переменные перед использованием или проверять на существование, и стараться не давать глобальным переменным имена, совпадающие с индексами массива $_SESSION.
    • Если вы используете перенаправление через header или навигацию с помощью JavaScript, PHP не пропишет необходимый идентификатор, т.к. он работает только со статичными ссылками. В этом случае надо проставлять идентификатор самостоятельно:
    header("Location: /script.php?".session_name().'='.session_id());

    Более детальный обзор можно найти на сайте phpfaq.ru

    Источник

Оцените статью