Introduction Sessions are actually very simple. You just need to understand what they are for and how they are arranged. We first answer the first question. As shown in the corresponding section of this FAQ, the web server does not maintain a permanent connection with the client, and each request is processed as new, without any connection with the previous ones. That is, you can neither track requests from the same visitor, nor save variables for him between views of individual pages. Here, to solve these two problems, sessions were invented. Actually, sessions, if in a nutshell, is a mechanism that uniquely identifies the browser and creates a file for the browser on the server in which session variables are stored.
I will not describe in detail the need for such a mechanism. These are such textbook cases as a shopping cart in the e-store, authorization, as well as not quite trivial problems, such as protecting the interactive parts of the site from spam.
In principle, it is quite simple to make your own analogue of sessions, not as functional as the one built into PHP, but similar in essence. On cookies and database. When requesting a script, we look if the cookie came with a specific name. If there is no cookie, then put it and write a new line in the database with user data. If there is a cookie, then read from the database. With another request, we delete old records from the database and now we have a session mechanism. Totally easy. But there are some nuances that make it preferable to use the built-in session mechanism.
How are the sessions organized and how do they work? First you need to somehow identify the browser. To do this, you must give him a unique identifier and ask him to send it with each request. I am ashamed to admit, but when I first learned about the sessions, I thought that this was some kind of special mechanism, some new way of communicating the browser with the server – the session. That the session id is transmitted in some special way. The disappointment was cruel. Sessions use standard, well-known data transfer methods. Actually, others are just not there. The identifier is a regular variable. By default, its name is PHPSESSID. The task of PHP is to send it to the browser so that it returns it with the following request. From the FAQ section already mentioned, it is clear that a variable can be transferred only in two ways: in cookies or by a POST / GET request. PHP uses both options. For this are responsible two settings in
If only the first is enabled, then when the session starts (each time session_start () is called), the client is set to cook. The browser regularly returns this cookie for each subsequent request and PHP has a session ID. Problems begin if the browser does not return cookies. In this case, without receiving a cookie with an identifier, PHP will always start a new session, and the mechanism will not work.
If only the second is enabled, the cookie is not set. And what is happening, for the sake of which, basically, in fact, it is worth using the built-in session mechanism. After the script does its work, and the page is fully formed, PHP looks at it all and appends a session identifier to each link and each form. It looks like this: Index turns into Index and a hidden field is added to the forms. And the browser when you click on any link, or when you click on a button in the form, send the variable we need – the session ID! For obvious reasons, the identifier is added only to relative links.
Theoretically, in our self-made sessions with you on the basis of cookies and the base, you can add the ID transmission to all references with your own hands – and then our own sessions will work independently of the cookies. But, you will agree – it is more pleasant when someone else does this work?
By default, in the latest versions of PHP both options are enabled. What does PHP do in this case? Cook always exhibited. And links are auto-completed only if PHP does not detect a cookie with a session identifier. When the user for the first time during this session visits the site, he is put in a cookie and the links are supplemented. On the next request, if cookies are supported, PHP sees the cookie and stops adding links. If cookies do not work, then PHP continues to regularly add the ID to the links, and the session is not lost. Users who work with cookies will see a long link with an id only once.
Fuh. With the transfer of the identifier finished. It now remains to bind to it the data file on the server side. PHP will do it for us. Simply write session_start (); $ _SESSION [‘test’] = ‘Hello world!’ ; And PHP will write the test variable to the file associated with this session. Here is a very important note. The $ _SESSION array is special. In it, in fact, are the variables that we are going to make available in various scripts. To place a variable in a session, it is sufficient to assign it to the element of the $ _SESSION array. To get its value – just refer to the same element. An example will be slightly lower.
Garbage collection – the removal of obsolete PHP files is also engaged in itself. As well as data coding and a bunch of other necessary things. As a result of this care, working with sessions is very simple. Here we are, in fact, approached the example of the work of the sessions. The example is very small: We check if we have a counter variable in the session, if not, then create it with a value of 0, and then output its value and increment it by one. The increased value is written to the session, and the next time the script is called, the variable will have the value 1, and so on. Everything is very simple.
In order to have access to session variables on any pages of the site, you need to write ONLY ONE (!) Line at the very beginning of EVERY file in which we need sessions: session_start (); And then go to the elements of the $ _SESSION array. For example, the authorization check would look something like this: session_start (); if ($ _SESSION [‘authorized’] 1) header (Location: /
Remove variables from session. If you have register_globals = off, then just write unset ($ _SESSION [‘var’]); If not, then next to it you need to write session_unregister (‘var’);
Application area. It is very important to understand what the session should be used for and why not.
First, remember that sessions can only be used when the user himself needs them, and not to obstruct him. After all, he can at any time get rid of the identifier! Say, when checking that a person fills out a form, not a script, the user himself is interested in the session to work – otherwise he will not be able to send the form! But to limit the number of requests to the script session is no longer suitable – a malicious script simply will not return the identifier.
Thirdly, it is not necessary to start the session indiscriminately, to everyone entering the site. This will create a completely extra load. Do not use sessions on trifles – for example, in the counters. What spylog calls sessions, is considered, of course, based on statistics of visits, and not with the help of a session mechanism similar to that. In addition, take a search engine that indexes your site. If the search robot does not support cookies, then php will by default supply PHPSESSID to the links, which – agree – may not like the search engine much, which, according to rumors, doesn’t like dynamic links, and then there’s a new address ! If sessions are used to restrict access to a closed section of the site, then everything is just a search engine and should not index it. If you have to show the same page to both authorized and unauthorized users, then this trick will help – start the session only to those who entered the password, or to those who have already started the session. To do this, instead of just session_start (), we write to the beginning of each page if (isset ($ _REQUEST [session_name ()])) session_start (); Thus, We start the session only to those who sent the ID. Accordingly, it is necessary for the first time to send it to the user – at the time of authorization. If the name and span are correct – write session_start ()!
The most common errors that PHP throws when attempting to work with sessions are: Two of them, Warning: Cannot send session cookie – headers already sent: Cannot send session cache limiter – headers already sent are caused by the same reason, the solution is described in this faq here Third, Warning: open (/ tmp \ sess_SID, O_RDWR) failed: no such file or directory (2) in full_script_path on line number (it looked like Warning: Failed to write session data (files). Please verify that the current setting of
As it turns out, human intelligence has no limits, and therefore I have to explain: the third error message (it is impossible to find a directory) will INEVITABLY lead to the first two, since the error message is output to the browser and after it headings cannot be used. Therefore, do not rush to search for a premature conclusion, but first write down the correct path!
The next most common problem with sessions is the heavy legacy of register_globals. Do NOT give script variables names that match the indices in the $ _SESSION array! When register_globals = on, the values will overwrite each other, and you will get confused. And when register_globals = off, another error will appear: Your script possibly
If it does not work, but no messages are displayed, then add two lines to the very beginning of the script that are responsible for displaying ALL errors on the screen – it is quite possible that there are errors, but you just don’t see them. ini_set (‘display_errors’, 1); error_reporting (E_ALL); or see errors in error_log. In general, the topic of displaying error messages is beyond the scope of this article, so just make sure at least that you can see them. A little more detail about finding errors can be found in this section.
If you are sure that there are no errors, but the given example does not work anyway, then it is possible that the transfer of the URL via URL is not enabled in PHP, and the cookies for some reason do not work. See what you have with the cookies. In general, if sessions do not work for you, then first try to transfer the session identifier with your hands, that is, make a link and assign an identifier to it: At the same time, you should make sure that the directive is not included
If this example does not work, then the problem is either in trivial typos (half of the problems with sessions come from the incorrectly written variable name) or in a too old version of PHP: support for sessions appeared in the version
If the browser does not return cookies – check whether the cookies work at all. Make sure that the domain to which you are applying has a normal name (in which there is at least one dot and does not contain prohibited characters, for example underscores) and clean the browser cache – these are two main reasons why cookies may not work.
If the example from here works, and your own code is not, then the problem is obviously not in the sessions, but in the algorithm. Look for where you lost the variable, step by step transfer the example from here, debug your script.
It should be remembered that pkhp lochit session file. That is, if one of your scripts starts a session and takes a long time to execute, while the other is trying to start it with the same identifier at this time, it will hang. Therefore, in long-running scripts, you should start a session only when it is needed, and close it immediately, using session_write_close ()
It is also very rare, and it is completely incomprehensible from where it appears, the problem is that the setting
Security Security sessions – an extensive topic. Therefore, I’ll focus on a few highlights. The most typical one is not to pass the identifier through the address bar. This is written even in
An example of authorization using sessions Let’s illustrate all of the above with a small example: create a file
if (isset ($ _GET [‘action’]) AND $ _GET [‘action’] == logout) session_start (); session_destroy (); header (Location: http: //. $ _SERVER [‘HTTP_HOST’]. /); exit;
if (! isset ($ _SESSION [‘user_id’]))?