# Sessions
(opens new window) to the session_start function.
Example
This feature also introduces a new php.ini setting named session.lazy_write , which defaults to true and means that session data is only rewritten, if it changes.
# Session Locking
As we all are aware that PHP writes session data into a file at server side. When a request is made to php script which starts the session via session_start() , PHP locks this session file resulting to block/wait other incoming requests for same session_id to complete, because of which the other requests will get stuck on session_start() until or unless the session file locked is not released
The session file remains locked until the script is completed or session is manually closed. To avoid this situation i.e. to prevent multiple requests getting blocked, we can start the session and close the session which will release the lock from session file and allow to continue the remaining requests.
Now one will think if session is closed how we will read the session values, beautify even after session is closed, session is still available. So, we can still read the session data.
In php >= 7.0, we can have read_only session, read_write session and lazy_write session, so it may not required to use session_write_close()
# Manipulating session data
The $_SESSION variable is an array, and you can retrieve or manipulate it like a normal array.
(opens new window) for more reference how to work on an array.
Note that if you store an object in a session, it can be retrieved gracefully only if you have an class autoloader or you have loaded the class already. Otherwise, the object will come out as the type __PHP_Incomplete_Class , which may later lead to crashes
# Warning:
(opens new window) So it can be strongly recommended to never store any personal information in $_SESSION . This would most critically include credit card numbers, government issued ids, and passwords; but would also extend into less assuming data like names, emails, phone numbers, etc which would allow a hacker to impersonate/compromise a legitimate user. As a general rule, use worthless/non-personal values, such as numerical identifiers, in session data.
# Destroy an entire session
If you’ve got a session which you wish to destroy, you can do this with session_destroy()
Using session_destroy() is different to using something like $_SESSION = array(); which will remove all of the values stored in the SESSION superglobal but it will not destroy the actual stored version of the session.
Note: We use $_SESSION = array(); instead of session_unset() because the manual
Only use session_unset() for older deprecated code that does not use $_SESSION.
# Session name
# Checking if session cookies have been created
Session name is the name of the cookie used to store sessions. You can use this to detect if cookies for a session have been created for the user:
Note that this method is generally not useful unless you really don’t want to create cookies unnecessarily.
# Changing session name
You can update the session name by calling session_name() .
If no argument is provided into session_name() then the current session name is returned.
It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). The session name can’t consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.
# Safe Session Start With no Errors
Many developers have this problem when they work on huge projects, especially if they work on some modular CMS on plugins, addons, components etc. Here is solution for safe session start where if first checked PHP version to cover all versions and on next is checked if session is started. If session not exists then I start session safe. If session exists nothing happen.
This can help you a lot to avoid session_start error.
# Syntax
- void session_abort ( void )
- int session_cache_expire ([ string $new_cache_expire ] )
- void session_commit ( void )
- string session_create_id ([ string $prefix ] )
- bool session_decode ( string $data )
- bool session_destroy ( void )
- string session_encode ( void )
- int session_gc ( void )
- array session_get_cookie_params ( void )
- string session_id ([ string $id ] )
- bool session_is_registered ( string $name )
- string session_module_name ([ string $module ] )
- string session_name ([ string $name ] )
- bool session_regenerate_id ([ bool $delete_old_session = false ] )
- void session_register_shutdown ( void )
- bool session_register ( mixed $name [, mixed $. ] )
- void session_reset ( void )
- string session_save_path ([ string $path ] )
- void session_set_cookie_params ( int $lifetime [, string $path [, string $domain [, bool $secure = false [, bool $httponly = false ]]]] )
- bool session_set_save_handler ( callable $open , callable $close , callable $read , callable $write , callable $destroy , callable $gc [, callable $create_sid [, callable $validate_sid [, callable $update_timestamp ]]] )
- bool session_start ([ array $options = [] ] )
- int session_status ( void )
- bool session_unregister ( string $name )
- void session_unset ( void )
- void session_write_close ( void )
# Remarks
Note that calling session_start() even if the session has already started will result in a PHP warning.
Работа с сессиями (сеансами) в PHP 7
В данной заметке коротко о том, как использовать сеансы (сессии) в PHP, как они работают и как они связаны с файлами cookie (куки).
Что такое сессия в PHP?
Сессия — это механизм для сохранения информации на разных веб-страницах для идентификации пользователей при навигации по сайту или приложению. Сессия PHP представляет собой способ хранения информации в переменных сессии, которые могут быть использованы для аутентификации на нескольких веб-страницах. В отличие от куков, информация сессии не хранится на компьютере пользователя. Вместо этого сессия создает файл на сервере во временном каталоге.
Рекомендуется настроить путь для хранения сессий на сервере. Сделать это можно несколькими способами. Необходимо заранее создать указанные директории!
В файле .htaccess :
Выше варианты для глобальной конфигурации хранения сессий. Можно настраивать хранение сессий для каждого проекта отдельно. Для этого в проекте необходимо вызвать php функцию session_save_path() c указанием необходимого пути. Перед session_start() укажем путь для хранения сессий проекта:
Создание сессии (сеанса) в PHP
Для того, чтобы начать сеанс (запустить сессию), необходимо вызвать функцию session_start() . Данную функцию нужно запускать вначале каждой страницы, на которой мы хотим в дальнейшем прочитать данные из сессии.
При каждом вызове session_start() PHP сам отправляет куку в браузер пользователя.
С помощью аргументов (ассоциативный масс $options ) можно переопределить текущие директивы конфигурации сессий, которые указаны в php.ini . Список всех директив: здесь
Запись и чтение сессий
После того, как на сервере создался файл вида sess_. , в данную сессию можно записать информацию, а так же считать её от туда.
Завершение (очистка) сессии
Так как сессии часто используются для авторизации пользователей, то нужно иметь механизм «выхода» из системы. Для того, чтобы завершить сессию нам нужно:
- Очистить массив $_SESSION
- Удалить временное хранилище (файл сессии) на сервере
- Удалить сессионную куку (cookie).
- session_id() — уникальный идентификатор сессии
- session_name() — значение идентификатора сессии
Итоги
Пример использования сессии
В данном примере я покажу как можно использовать сессии (сеансы) в PHP на практике. Для начала на сервере создадим файл index.php со следующим содержимым:
Здесь я постарался максимально понятно описать всё происходящее. Под пользователя при заходе на эту страницу уже создаётся сессия, она пустая, это пока просто файл. Если пользователь заполнил все необходимые поля формы и нажал кнопку `Отправить`, то созданный файл (файл сессии) заполниться данными. Далее скрипт проверяет, если есть в сессии данные именно этого пользователя (здесь он уже сравнивает с кукой, которая пришла до этого на машину пользователя), то выводим эти данные. В противном случае, добавляем в сессию данные пользователя.
Функции для работы с сессиями
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:
<?php
if( version_compare ( phpversion (), ‘4.3.0’ )>= 0 ) <
if(! ereg ( ‘^SESS[0-9]+$’ , $_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:
<?php
header ( ‘location: script.php?’ . session_name (). ‘=’ . session_id ()
. ‘&SESSION_NAME=’ . session_name ());
?>
<input type=»image» src=»button.gif» onClick default»><?php
echo session_name (); ?> = <?php echo session_id (); ?> &SESSION_NAME= <?php echo session_name (); ?> ‘)» />
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_destroy
session_destroy() destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, session_start() has to be called.
Note: You do not have to call session_destroy() from usual code. Cleanup $_SESSION array rather than destroying session data.
In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. setcookie() may be used for that.
When session.use_strict_mode is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling session.use_strict_mode is recommended for all sites.
Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links.
Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly.
To avoid these, you must set deletion time-stamp to $_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to session_regenerate_id() also.