- Функции для работы с сессиями
- PHP Sessions
- What is a PHP Session?
- Start a PHP Session
- Example
- Get PHP Session Variable Values
- Example
- Example
- Modify a PHP Session Variable
- Example
- Destroy a PHP Session
- Example
- session_destroy
- Список параметров
- Возвращаемые значения
- Примеры
- Смотрите также
- User Contributed Notes 4 notes
Функции для работы с сессиями
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 ( ‘^SESS7+$’ , $_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.
PHP Sessions
A session is a way to store information (in variables) to be used across multiple pages.
Unlike a cookie, the information is not stored on the users computer.
What is a PHP Session?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.
Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
So; Session variables hold information about one single user, and are available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.
Start a PHP Session
A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
Now, let’s create a new page called «demo_session1.php». In this page, we start a new PHP session and set some session variables:
Example
// Set session variables
$_SESSION[«favcolor»] = «green»;
$_SESSION[«favanimal»] = «cat»;
echo «Session variables are set.»;
?>
Note: The session_start() function must be the very first thing in your document. Before any HTML tags.
Get PHP Session Variable Values
Next, we create another page called «demo_session2.php». From this page, we will access the session information we set on the first page («demo_session1.php»).
Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page ( session_start() ).
Also notice that all session variable values are stored in the global $_SESSION variable:
Example
// Echo session variables that were set on previous page
echo «Favorite color is » . $_SESSION[«favcolor»] . «.
«;
echo «Favorite animal is » . $_SESSION[«favanimal»] . «.»;
?>
Another way to show all the session variable values for a user session is to run the following code:
Example
How does it work? How does it know it’s me?
Most sessions set a user-key on the user’s computer that looks something like this: 765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session.
Modify a PHP Session Variable
To change a session variable, just overwrite it:
Example
// to change a session variable, just overwrite it
$_SESSION[«favcolor»] = «yellow»;
print_r($_SESSION);
?>
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and session_destroy() :
Example
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
session_destroy
session_destroy() уничтожает все данные, связанные с текущей сессией. Данная функция не удаляет какие-либо глобальные переменные, связанные с сессией и не удаляет сессионные cookie. Чтобы вновь использовать переменные сессии, следует вызвать session_start() .
Замечание: Нет необходимости вызывать session_destroy() в обычном коде. Очищайте массив $_SESSION вместо удаления данных сессии.
Чтобы полностью удалить сессию, также необходимо удалить и её идентификатор. Если для передачи идентификатора сессии используются cookie (поведение по умолчанию), то сессионные cookie также должны быть удалены. Для этого можно использовать setcookie() .
При включённой опции session.use_strict_mode, вам не нужно удалять устаревшие cookie идентификатора сессии. В этом нет необходимости, потому что модуль сессии не примет cookie идентификатора сессии, если с этим идентификатором сессии нет связанных данных, и модуль сессии установит новый cookie идентификатора сессии. Рекомендуется включать опцию session.use_strict_mode для всех сайтов.
Немедленное удаление сессии может привести к нежелательным последствиям. При наличии конкурирующих запросов, другие соединения могут столкнуться с внезапной потерей данных сессии, например, это могут быть запросы от JavaScript и/или запросы из ссылок URL.
Даже если текущий модуль сессии не поддерживает пустые cookie идентификатора сессии, немедленное удаление сессии может привести к пустым cookie идентификатора сессии из-за состояния гонки на стороне клиента (браузера). Это приведёт к тому, что клиент создаст множество идентификаторов сессии без необходимости.
Чтобы этого избежать, необходимо установить в $_SESSION временную метку удаления и убрать доступ позже. Или удостовериться, что ваше приложение не имеет конкурирующих запросов. Это также относится к session_regenerate_id() .
Список параметров
У этой функции нет параметров.
Возвращаемые значения
Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
Примеры
Пример #1 Уничтожение сессии с помощью $_SESSION
// Инициализируем сессию.
// Если вы используете session_name(«something»), не забудьте добавить это перед session_start()!
session_start ();
?php
// Удаляем все переменные сессии.
$_SESSION = array();
// Если требуется уничтожить сессию, также необходимо удалить сессионные cookie.
// Замечание: Это уничтожит сессию, а не только данные сессии!
if ( ini_get ( «session.use_cookies» )) $params = session_get_cookie_params ();
setcookie ( session_name (), » , time () — 42000 ,
$params [ «path» ], $params [ «domain» ],
$params [ «secure» ], $params [ «httponly» ]
);
>
// Наконец, уничтожаем сессию.
session_destroy ();
?>
Смотрите также
- session.use_strict_mode
- session_reset() — Реинициализирует сессию оригинальными значениями
- session_regenerate_id() — Генерирует и обновляет идентификатор текущей сессии
- unset() — Удаляет переменную
- setcookie() — Отправляет cookie
User Contributed Notes 4 notes
If you want to change the session id on each log in, make sure to use session_regenerate_id(true) during the log in process.
session_start ();
session_regenerate_id ( true );
?>
It took me a while to figure out how to destroy a particular session in php. Note I’m not sure if solution provided below is perfect but it seems work for me. Please feel free to post any easier way to destroy a particular session. Because it’s quite useful for functionality of force an user offline.
1. If you’re using db or memcached to manage session, you can always delete that session entry directly from db or memcached.
2. Using generic php session methods to delete a particular session(by session id).
$session_id_to_destroy = ‘nill2if998vhplq9f3pj08vjb1’ ;
// 1. commit session if it’s started.
if ( session_id ()) session_commit ();
>
// 2. store current session id
session_start ();
$current_session_id = session_id ();
session_commit ();
// 3. hijack then destroy session specified.
session_id ( $session_id_to_destroy );
session_start ();
session_destroy ();
session_commit ();
// 4. restore current session id. If don’t restore it, your current session will refer to the session you just destroyed!
session_id ( $current_session_id );
session_start ();
session_commit ();
I’m using PHP 7.1 and received the following warning when implementing Example #1, above:
PHP message: PHP Warning: session_destroy(): Trying to destroy uninitialized session in.
What I discovered is that clearing $_SESSION and removing the cookie destroys the session, hence the warning. To avoid the warning while still keeping the value of using session_destroy(), do this after everything else:
if (session_status() == PHP_SESSION_ACTIVE)
All of a sudden neither session_destroy() nor $_SESSION=[] were sufficient to log out. I found the next to work:
setcookie ( session_name (), session_id (), 1 ); // to expire the session
$_SESSION = [];
?>
- Функции для работы с сессиями
- 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