You get a bonus - 1 coin for daily activity. Now you have 1 coin

Sessions in PHP link with cookies

Lecture



A detailed description of the work and an explanation of the mechanism for working with PHP sessions.


Sessions in PHP link with cookies
Introduction

Sessions are really very simple. You just need to understand what they are for and how they are arranged. Answer first to the first question.
Perhaps you know that the web server does not support a permanent connection with the client, and each request is processed as new, without connection with the previous ones.

That is, you can neither track requests from the same visitor, nor save for him variables between views of individual pages. Here, to solve these two problems, sessions were invented.
Actually, sessions, if in a nutshell, is a mechanism for uniquely identifying the browser and creating 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 cases such as a shopping cart in an online store, authorization, as well as not quite trivial problems, such as, for example, protection of interactive parts of a 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 cookies have come with a specific name. If there are no cookies, then put it and write a new line in the database with user data. If there are cookies, then read from the database. Another request removes 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. For this you need to 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, a new way of communicating the browser with the server - the “session”. That the session id is transmitted in some special way. But 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 passed only in two ways: in cookies or in a POST / GET request.
PHP uses both options.

Two settings in php.ini are responsible for this:

session.use_cookies - if equal to 1, then PHP sends the identifier to cookies, if 0 - then no.
session.use_trans_sid if equal to 1, then PHP sends it, adding to the URL and forms, if 0 - then no.

You can change these and other session parameters in the same way as other PHP settings - in the php.ini file, as well as using the ini_set() or in the web server configuration files

If only the first one is enabled, then when the session starts (each time session_start () called), the client is set cookies. The browser regularly returns each cookie to this cookie and PHP has a session ID. Problems begin if the browser does not return cookies. In this case, without receiving cookies with an identifier, PHP will always start a new session, and the mechanism will not work.

If only the second one is enabled, cookies are 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 ID to each link and each form. It looks like this:

Index

turns into

Index

a hidden field is added to the forms

And when a browser clicks on any link, or when a button is clicked on a form, it will send the variable we need in the request - the session identifier!

Theoretically, in our self-made cookies and base sessions with you, you can add your own ID to all the links with your hands - and then our own sessions will work regardless of cookies. But, you will agree - it is more pleasant when someone else does this work? ;-)

By default, both options are included in recent PHP versions. What does PHP do in this case? Cook always exhibited. Links are auto-completed only if PHP does not detect cookies with a session identifier. When a user visits a site for the first time during this session, he is put in cookies and links are added. On the next request, if cookies are supported, PHP sees cookies and stops adding links. If cookies do not work, then PHP continues to regularly add IDs to the links, and the session is not lost.
Users who work with cookies will see a long link with an ID only once.

With the transfer of the identifier finished. Now it remains to bind to it the data file on the server side. PHP will do it for us. Just 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 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 sessions.
The example is very small:

session_start ();
if (!isset(
$_SESSION [ 'counter' ])) $_SESSION [ 'counter' ]= 0 ;
echo
"Вы обновили эту страницу " . $_SESSION [ 'counter' ]++. " раз. " ;
echo
"
$_SERVER [ 'PHP_SELF' ]. ">обновить" ;
?>

We check if we have a counter variable in the session, if not, 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 array $ _SESSION. For example, the authorization check will look something like this:

session_start ();
if (
$_SESSION [ 'authorized' ]<> 1 ) {
header ( "Location: /auth.php" );
exit;
}

Remove variables from session. If you have register_globals=off , then just write

unset( $_SESSION [ 'var' ]);

If not, then you should write next to it:

session_unregister ( 'var' );

Application area

It is very important to understand why a session should be used and why not.

First, remember that sessions can be used only 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.

Secondly. It is important to clearly imagine the fact that the session is a session with the site, as it is understood by the person. Came, worked, closed the browser - the session ended. Like a movie session. Want to see another one - buy a new ticket. Start a new session. There is a technical explanation for this. The guaranteed session mechanism works only until the browser is closed. After all, the client may not work cookies, and in this case, of course, all links supplemented by the identifier will be lost with its closure.

True, the session may disappear without closing the browser. Due to the limitations discussed in this article, the session mechanism cannot determine when the user has closed the browser. To do this, use a timeout - a predetermined time, after which we believe that the user has left the site. By default, this parameter is 24 minutes.

If you want to save user information for a longer period, use cookies and, if necessary, a database on the server. In particular, this is how all popular authorization systems work:

- upon identification of the user, the session starts and the sign of authorization is transmitted in it.
- If you need to "remember" the user, then he put the cookie, identifying it.
- The next time the user logs on to the site, in order to log in, he must either enter the password, or the system will recognize it by the cookies set earlier, and start the session. New session, but not continuing the old one.

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 the statistics of sunset, and not using the mechanism of sessions, similar to PHP.

In addition, take the search engine that indexes your site. If the search robot does not support cookies, then PHP will deliver PHPSESSID to the links by default, which the search engine may not like very much, which, according to rumors, doesn’t like dynamic links, and then every time you call it, the 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, at the beginning of each page instead of just session_start () we write:

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

Possible problems and their elimination

The most common errors that PHP throws when trying to work with sessions are:
Two of them

Warning: Cannot send session cookie - headers already sent
Warning: Cannot send session cache limiter - headers already sent

caused by the same reason, the solution is described in this fake here

Third,

Warning: open(/tmp\sess_SID, O_RDWR) failed: No such file or directory (2) in full_script_path on line number

she previously looked like

Warning: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) Warning: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/tmp) ,

if you translate it from English, the problem is explained in detail: the path to the directory in which the session files are written is not available. This error is the easiest to fix. Just register a directory that exists and is available for writing, for example,

session.save_path = c:\windows\temp

And don't forget to restart Apache after that.

As it turns out, human acumen has no limits, and therefore I have to explain:
the third error message (it is impossible to find the directory) will inevitably lead to the appearance of the first two, since the error message is output to the browser and after it the headers 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.

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 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 PHP did not enable the transmission through the URL, and cookies for some reason do not work .
See what you have with cookies.

Generally, if your sessions do not work, then first try passing the session identifier with your hands, that is, making a link and assigning an identifier to it:

if the browser returns cookies other than the session ID.

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.

Another problem may arise if you use redirection through a header or navigation using javascript.
The fact is that PHP automatically adds a session identifier only to links of the form
, but does not do this for , javascript, meta tags.

Therefore, it is necessary to add an identifier by hand, for example, like this:

header ( "Location: /script.php?" . session_name (). '=' . session_id ());

It is also very rare, and it is completely incomprehensible where it comes from, the problem is that the setting of session.save_handler is different from files. If not, correct it.

Additional Information:

  • In addition to cookies, the session mechanism also sends headers that prohibit page caching (the same cache limiter). For html it is correct and necessary. But when you try to give a file to the authorization script, the Internet Explorer refuses to download it. It is because of this heading. Call
    session_cache_limiter ( "private" );
    Before the start of the session should solve the problem.
  • Strange as it may seem, but in the $_SESSION you cannot use numeric indices - $_SESSION [ 1 ], $_SESSION [ '10' ] - the sessions will not work.
  • Somewhere between versions 4.2 and 5.0, it was impossible to set session.use_trans_sid with ini_set () . Starting from 5.0 already possible again.
  • Prior to version 4.3.3 of cookies, PHP sent cookies only if there was no identifier in the request when the session started. Now, cookies are sent each time session_start () called.

Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Running server side scripts using PHP as an example (LAMP)

Terms: Running server side scripts using PHP as an example (LAMP)