Computers Windows Internet

HTTP session. How to configure the parameters of a terminal server remote connection session? Once again about the session_name () and session_id () functions

The web server does not maintain a persistent connection to the client, and each request is treated like a new one, without any connection to the previous ones.
That is, you can neither track requests from the same visitor, nor save variables for him between views of separate pages. Sessions were invented to solve these two problems.
Actually, sessions, if in a nutshell, is a mechanism that allows you to uniquely identify a browser and creates a file for this browser on the server, which stores session variables.

I will not describe in detail the need for such a mechanism. These are such textbook cases as a shopping cart in an e-store, authorization, as well as not entirely trivial problems, such as, for example, protecting interactive parts of the site from spam.

In principle, it is quite easy to make your own analog of sessions, not as functional as the built-in PHP, but similar in essence. On cookies and database.
When requesting a script, we look to see if a cookie has arrived with a specific name. If there is no cookie, then set it and write a new line with user data to the database. If there is a cookie, then we read from the database. With one more request, we delete old records from the database, and now we have a session mechanism ready. It's not difficult at all. But there are some nuances that make it preferable to use the built-in session mechanism.

If only the first is enabled, then at the start of the session (with each call to session_start ()) a cookie is set to the client. The browser correctly returns this cookie with every next request, and PHP has a session identifier. Problems begin if the browser does not return cookies. In this case, PHP will always start a new session without receiving cookies with an identifier, and the mechanism will not work.

If only the second is enabled, then the cookie is not set. And what happens is, for the sake of which, basically, in fact, it is worth using the built-in session mechanism. After the script does its job, and the page is fully formed, PHP looks at it all and appends a session ID to each link and to each form. It looks something 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, will send in the request the variable we need - the session identifier!
For obvious reasons, the ID is only added to relative links.

Theoretically, in our homemade sessions on cookies and a database, you can manually assign the transfer of id to all the links by hand - and then our own sessions will work independently of the cookies. But, you see - it's more pleasant when someone else does this work? ;-)

Both options are enabled by default in recent versions of PHP. How does PHP handle this? Cook is always exhibited. And links are autocompleted only if PHP does not find a cookie with a session ID. When a user visits the site for the first time during this session, he gets a cookie, and links are added. On the next request, if cookies are supported, PHP sees the cookie and stops completing links. If the cookies do not work, then PHP continues to properly add id to links, and the session is not lost.
Users who have cookies working will see the long link with the id only once.

Fuh. With the transfer of the identifier finished.
Now it remains to bind a file with data on the server side to it.
PHP will do this for us. It's enough just to write
session_start ();
$ _SESSION ["test"] = "Hello world!";

And PHP will write the test variable to the file associated with this session.
There is a very important point here.
The $ _SESSION array is special.
In it, in fact, are the variables that we want to make available in various scripts.
To place a variable in a session, just assign it to an element of the $ _SESSION array.
To get its value, it is enough to refer to the same element. An example will be below.

Garbage collection - PHP is also involved in removing obsolete files. As well as data encoding and a bunch of other necessary things. As a result of this care, working with sessions is very easy.
Here we are, in fact, and come to the example of the work of sessions.
The example is very small:
session_start ();

echo "You have updated this page". $ _ SESSION ["counter"] ++. "times.";
echo "
update ";
?>

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 increase it by one. The increased value will be 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 EACH file in which we need sessions:
session_start ();
And then refer to the elements of the $ _SESSION array. For example, an authorization check would look something like this:
session_start ();
if ($ _SESSION ["authorized"]<>1) {
header ("Location: /auth.php");
exit;
}

Removing variables from a session.
If you have register_globals = off, then just write
unset ($ _ SESSION ["var"]);
If not, then near I need to write with her
session_unregister ("var");

The most common errors that PHP gives 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 fact
Third,
Warning: open (/ tmp \ sess_SID, O_RDWR) failed: No such file or directory (2) in full_script_path on line number(previously she looked like Warning: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/ tmp)),
if translated from English, it explains the problem in detail: the path specified in php.ini to the directory where the session files are written is not available. This error is the easiest to fix. Just write a directory that exists and is writable, for example,
session.save_path = c: \ windows \ temp
And don't forget to restart the Apache after that.

As it turns out, human intelligence has no limits, and therefore I have to explain:
the third error message (directory cannot be found) will UNAVAILABLE lead to the first two, because the error message is output to the browser and you cannot use headers after it. Therefore, do not rush to look for a premature conclusion, but first write the correct path!

The next most common problem when dealing with sessions is the heavy legacy of register_globals. DO NOT give script variables the same names as the indices of the $ _SESSION array!
With register_globals = on, the values ​​will overwrite each other and you get confused.
And if register_globals = off, another error will appear: "Your script possibly relies on a session side-effect which existed until PHP 4.2.3." ... To get rid of it, you should always initialize variables before use (or at least check for existence) and do not give global variables names that match the indices of the $ _SESSION array.

If it does not work, but no messages are displayed either, then add two lines at 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 simply do not 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 you can see them. You can read a little more detail about troubleshooting 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 does not enable the transfer of id via url, and cookies for some reason do not work.
See what you have with cookies.
In general, if your sessions "do not work", then first try to transfer the session identifier by hand, that is, make a link and assign an identifier to it:
session_start ();
if (! isset ($ _ SESSION ["counter"])) $ _SESSION ["counter"] = 0;
echo "You have updated this page". $ _ SESSION ["counter"] ++. "times.

update ";
?>

When doing this, make sure that the session.use_only_cookies directive is not enabled, which prevents PHP from accepting a session ID if it was passed through a URL.

If this example does not work, then the problem is either in the banal typos(half of the "problems" with sessions come from a misspelled variable name), or in a too old version of PHP: session support appeared in version 4.0, and the $ _SESSION array - in 4.1 (Before that, $ HTTP_SESSION_VARS was used).
If it works, then the problem is in the cookies. Track what kind of cookie the server is putting to the browser, whether the browser returns it. Searching is very useful while looking at the HTTP header exchanges between the browser and the server.
Explaining how cookies work is beyond the scope of this already too large text, but at least make sure that the server sends the cookie with the identifier, and the browser returns. And while the identifiers coincide with each other =)
Setting the cookie should look like
Set-Cookie: PHPSESSID = prlgdfbvlg5fbsbshch6hj0cq6;
or how
Set-Cookie: PHPSESSID = prlgdfbvlg5fbsbshch6hj0cq6; path = /
(if you are requesting a script not from the root directory)
The server response should look like
Cookie: PHPSESSID = prlgdfbvlg5fbsbshch6hj0cq6
or
Cookie: PHPSESSID = prlgdfbvlg5fbsbshch6hj0cq6; b = b
if the browser returns other cookies besides the session ID.

If the browser does not return cookies, check if cookies work at all.
Make sure that the domain you are accessing has a normal name (which has at least one period and does not contain prohibited characters, such as underscores) and clear your browser cache - these are two main reasons why cookies may not work.

If the example from here works, but your own code does not, then the problem is obviously not in the sessions, but in the algorithm. Look for where you lost the variable, transfer the example from here step by step, debug your script.

Another problem can arise if you are using header redirection or JavaScript navigation.
The fact is that PHP automatically appends the session identifier only to links of the form
, but does not do this for headers, javascript, meta tags.
Therefore, you need to add the identifier by hand, for example, like this:
header ("Location: /script.php?". session_name (). "=". session_id ());

Also, very rare, and it is completely unclear where the problem comes from, the problem is that the session.save_handler setting has a value other than files. If this is not the case, correct it.

Safety
Session security is a vast topic. Therefore, I will focus on a few main points.
The most textbook thing is not to pass the identifier through the address bar. This is written even in php.ini, but this limits the functionality of sessions. If you decide to follow this advice, then besides session.use_trans_sid = 0, do not forget session.use_only_cookies = 1
It is advisable to bind the session to an IP address: this way, if the identifier is stolen, the villain will still not be able to use it in most cases.
It is recommended to use the session.save_path directive, with the help of which you can set your own directory for saving session files. This is more secure than when they are stored in the server's default shared temporary directory.

Additional Information:

  • In addition to cookies, the session mechanism also sends headers that prohibit page caching (the same cache limiter). For html, this is correct and necessary. But when you try to send a file with a script that checks authorization, the Internet Explorer refuses to download it. It is because of this title. Call
    session_cache_limiter ("private");
    must solve the problem before starting the session.
  • Strange as it may seem, but you cannot use numeric indices in the $ _SESSION array - $ _SESSION, $ _SESSION ["10"] - sessions will not work.
  • Somewhere between 4.2 and 5.0 it was not possible to set session.use_trans_sid using ini_set (). Starting from 5.0 it is already possible again.
  • Prior to version 4.3.3, the PHP cookie sent a cookie only if the request did not contain an identifier at the start of the session. Now the cookie is sent every time session_start () is called.

    An example of authorization using sessions
    Let's illustrate all of the above with a small example:
    let's create auth.php file:
    if (isset ($ _ POST ["auth_name"]))
    {
    $ sql = "SELECT * FROM users WHERE name =? S";
    $ row = $ db -> getRow ($ sql, $ _POST ["auth_name"]);
    if ($ row && password_verify ($ _POST ["auth_pass"], $ row ["pass"])) (
    $ _SESSION ["user_id"] = $ row ["id"];
    }
    header ("Location: http: //". $ _SERVER ["HTTP_HOST"]. $ _SERVER ["REQUEST_URI"]);
    exit;
    }

    if (isset ($ _ GET ["action"]) AND $ _GET ["action"] == "logout") (
    session_start ();
    session_destroy ();
    header ("Location: http: //". $ _SERVER ["HTTP_HOST"]. "/");
    exit;
    }

    if (! isset ($ _ SESSION ["user_id"])) (
    ?>








    exit;
    }

    Now it is enough to write in all protected scripts the line
    require "auth.php";
    In this example, it is assumed that the session has already started and the connection to the database has been created using Class for safe and convenient work with MySQL. It also assumes that the password has been hashed using the recommended password_hash function.
    An example of a protected file:

    session_start ();
    include "safemysql.class.php";
    $ db = new safemysql (["db" => "test"]);
    include "auth.php";
    ?>
    secret

    logout

    OPS! Very Useful Links:
    http://www.php.net/manual/ru/ref.session.php - the most recent and up-to-date information on session support in PHP in the official documentation, plus numerous user comments. Reading highly recommended.
    http://phpclub.ru/manrus/f/ref.session.html - VERY outdated translation of this chapter into Russian, from the documentation translated by Alexander Pyramidin.
    http://phpclub.ru/detail/article/sessions
    An article with a pretentious title "The Truth About Sessions". It leaves an ambivalent impression. At the beginning, the author talks about the session mechanism VERY easily, but the methods that he proposes towards the end of the article are completely muddy.

    Textbook article by Dmitry Borodin from the site
    http://php.spb.ru/ is strongly NOT recommended.
    Guys, she's terribly out of date. Not only are there factual inaccuracies in it, but sessions in PHP have simply not been used for a long time.
    Many thanks to Dima for her, this was the first article on sessions in Russian, I studied it myself, but now I need to send her to a well-deserved rest.
    Also, unfortunately, many other articles that are on the Internet and have not been updated for years are also outdated.

  • Session (from Latin - sessio - meeting, English - session) is a period of time covering the user's work on the Internet from the moment of opening the first to the last links. It is calculated as the difference in time between the initial and final requests. However, the last page can be viewed by the user for different times, from which, therefore, measuring the time between two requests becomes more difficult.

    How session is related to HTTP and COOKIES

    What a session is can be explained in terms of the HTTP protocol. By itself, this protocol does not provide a way to persist state between two operations. That is, in other words, by opening one page and then going from it to another, HTTP will not be able to establish that both requests belong to the same user. And this is where a special tracking method comes to the rescue - session management (our sessions).
    Hence, answering the question of what a session is, we can say that it is an auxiliary logical object that facilitates the transfer of data between successive HTTP requests from one user.
    Cookies, like a session, store information about the user as he navigates through different pages and improve the operation of the protocol. But unlike the second, where data is stored in temporary files on the server, they save them on the user's computer in the form of small fragments.

    What are sessions for?

    The use of sessions becomes indispensable when working with sites such as forums, message boards and online stores, because in this case it is necessary to save user data over several pages.

    Session stages

    The entire session can be divided into three stages:

    • opening a session (when a user starts working with a specific site),
    • accounting for session variables (when going to different pages),
    • end of the session.

    Due to the fact that session data is stored on a third-party server, it is best not to store large amounts of information in them, but to use cookies.


    Sessions in PHP or how data about a user or customer who has entered the site is saved when navigating between the pages of the site without much difficulty. The lesson is very important. Relevant for the creation of 95% of sites.

    What is session in php

    Sessions are used to store information about temporary data (for example, that the user has entered the site) when navigating between pages of the same site. When using sessions, data is saved in temporary files on the server.
    Most often, sessions (and cookies, by the way, too) are used when creating online stores, forums, message boards, social networks, blogs and other resources. The convenience of the session system consists in storing the temporary information of the logged in user / customer, the data about which is in quick access for a certain time. The session has a natural expiration date - until the browser is closed. If you close only the page, then when you open the site, the data about the user / buyer will still be available.

    Session logic

    Session (or session) is a kind of temporary data storage. I warn you right away that it is worth saving a small amount of data. For example, the login and password of the logging in user or his serial number in the database.

    Example of work
    1. The user enters a username and password and enters the site
    2. Data with login and password are saved in the session of one of the pages of the site:

    File index.php

    Session_start (); // each file in which you want to use session data must contain the "start session" command at the beginning of the code

    $ login = "admin";
    $ password = "pass";
    $ _SESSION ["login"] = $ login; // save the variable containing the login
    $ _SESSION ["password"] = $ password; // save the variable containing the password

    3. When you go to another page of the site, this data will also be available:

    File example.php(or any other page)

    Echo "Your login". $ _ SESSION ["login"]; // will display "Your login is admin", although we did not record data on this page!
    See, it's simple!

    4. If you want to clear the session data, then it is enough:

    File example.php

    Session_start (); // "start the session" again

    Unset ($ _ SESSION ["login"]); // this is how the variable was unregistered or "destroyed"
    echo "Your login". $ _ SESSION ["login"]; // will display "Your login". Since we destroyed it in the last line, there is no data either.

    Session_destroy (); // destroy the session. All data including $ _SESSION ["password"] is gone. When requested, an error will be displayed
    In general, such a transfer is similar to the POST method, but you no longer have to write a lot of unnecessary code, and all data transferred from page to page is stored in temporary files on the server. Again, sessions should contain small amounts of data, so they are suitable for storing username / password, shopping cart and other small volumes.

    Passing a value or array using a PHP session

    In a session, you can write not only a string, but also an array of data. Just do not overdo it with the size of the array, as all this will affect the performance and the occupied space on the server.

    We use a certain start page again index.php

    Session_start ();

    $ r = array ("one", "two", "three");

    $ _SESSION ["arr"] = $ r;

    To the page where everything is displayed
    We saved the data in the session and follow the link to another page, where we will display all the data.

    File recipient, page test.php where we open the array

    Session_start ();
    print_r ($ _ SESSION ["arr"]);
    // will output
    /*
    Array
    => one
    => two
    => three
    */
    ?>
    You might want to brush up on a tutorial on. In general, everything should be clear.

    Other functions for working with sessions

    session_unregister (string)- the session forgets the value of the specified global variable;
    session_destroy ()- the session is destroyed (for example, if the user has left the system by pressing the logout button);
    session_set_cookie_params (int lifetime [, string path [, string domain]])- using this function, you can set how long the session will live by setting unix_timestamp, which determines the time of death of the session.

    List of functions for working with sessions (session) in php
    session_cache_expire - Returns the expiration of the current cache
    session_cache_limiter - Get and / or set the current cache limit
    session_commit - an alias for session_write_close ()
    session_decode - Decodes session data from string
    session_destroy - Destroys all data registered for the session
    session_encode - encrypts current session data as a string
    session_get_cookie_params - Get session cookie parameters
    session_id - gets and / or sets the current session id
    session_is_registered - determines if a variable is registered in the session
    session_module_name - Get and / or install the module for the current session
    session_name - gets and / or sets the name of the current session
    session_regenerate_id - Modifies the current session id with the newly generated one
    session_register - registers one or more variables for the current session
    session_save_path - gets and / or sets the path to save the current session
    session_set_cookie_params - sets session cookie parameters
    session_set_save_handler - sets user-level session storage functions
    session_start - initializes session data
    session_unregister - Unregisters a variable from the current session
    session_unset - Releases all session variables
    session_write_close - Writes session data and end of session

    Session examples

    The counter of page views during the session. An illustrative example of work. However, after closing the browser, the countdown will start over.

    Counter of visits to one page within one session

    // A simple example of using sessions without cookies.
    session_name ("test");
    session_start ();
    $ _SESSION ["count"] = @ $ _ SESSION ["count"] + 1;
    ?>

    Counter


    In the current session of work with the browser, you have opened this page
    time (s).
    Close your browser to reset this counter.
    Click here to refresh the page!
    With each transition, the counter will increase by 1)

    Thank you for your attention! Good luck in your endeavors!

    Since HTTP is a client-server protocol, an HTTP session consists of three phases:

    1. The client establishes TCP connections (or another connection if TCP transport is not used).
    2. The client sends a request and waits for a response.
    3. The server processes the request and sends a response containing the status code and related data.

    Starting in HTTP / 1.1, after the third phase, the connection is not closed because the client is allowed to initiate another request. That is, the second and third phases can be repeated.

    Establishing a connection

    Since HTTP is a client-server protocol, the connection is always established by the client. Opening a connection in HTTP means establishing a connection through the appropriate transport, usually TCP.

    In the case of TCP, port 80 is used as the default HTTP server port on the computer, although others are also often used, such as 8000 or 8080. The URL of the loaded page contains the domain name and port, which can be omitted if it matches the default port.

    We mean: The client-server model prevents the server from sending data to the client without explicitly requesting that data. To work around this problem, web developers use various techniques: periodically ping the server using the XMLHTTPRequest Javascript object, the HTML WebSockets API, or similar protocols.

    Sending a customer request

    When the connection is established the user-agent can send a request. (the user-agent is usually a web browser, but it may not be) The client request is text directives separated by CRLF (line break). The request itself includes three blocks:

    1. The first lines contain the request method and its parameters:
      • path to document - absolute URL without specifying protocol and domain name
      • HTTP protocol version
    2. Each subsequent line is an HTTP header and sends to the server some information about the types of preferred data (for example, what language, what MIME types) or instructions that change the server's behavior (for example, do not send a response if it is already in the cache). These HTTP headers form a block that ends with an empty line.
    3. The last block is optional and contains additional data. Mostly used by the POST method.

    Examples of requests

    We get the main page of the site, and tell the server that the user-agent prefers the page in French, if possible:

    GET / HTTP / 1.1 Host: site Accept-Language: fr

    Pay attention to the blank line at the end, which separates the data block from the header block. Since the request does not contain the Content-Length: HTTP header, the data block is empty and the server can start processing the request as soon as it receives an empty string indicating the end of the headers.

    We send the result of the form submission:

    POST /contact_form.php HTTP / 1.1 Host: site Content-Length: 64 Content-Type: application / x-www-form-urlencoded name = Joe% 20User & request = Send% 20me% 20one% 20of% 20your% 20catalogue

    Request Methods

    HTTP defines a set of request methods indicating the desired action on the resource. Although they can also be nouns, these request methods are sometimes referred to as HTTP commands. The most common GET and POST requests are:

    • GET is used to request the content of the specified resource. A request using GET should only receive data.
    • The POST method sends data to the server so that it can change its state. This method is often used for HTML forms.

    Server response structure

    After the attached agent has sent its request, the web server processes it and sends a response. By analogy with the client request, the server response is text directives separated by CRLF, grouped into three different blocks:

    1. The first line - the status line, consists of a confirmation of the used HTTP version and the status of the request (and its value in a human-readable form).
    2. Subsequent lines are HTTP headers that give the client some information about the data being sent (eg type, size, compression algorithm, caching hints). As with the client request, these HTTP headers form a block terminated with an empty line.
    3. The last block contains data (if any).

    Sample responses

    Successful web page retrieval:

    HTTP / 1.1 200 OK Date: Sat, 09 Oct 2010 14:28:02 GMT Server: Apache Last-Modified: Tue, 01 Dec 2009 20:18:22 GMT ETag: "51142bc1-7449-479b075b2891b" Accept-Ranges: bytes Content-Length: 29769 Content-Type: text / html(here goes the 29769 bytes of the requested webpage)

    The message that the requested resource has been moved:

    HTTP / 1.1 301 Moved Permanently Server: Apache / 2.2.3 (Red Hat) Content-Type: text / html; charset = iso-8859-1 Date: Sat, 09 Oct 2010 14:30:24 GMT Location: (this is the new address of the requested resource, the client is expected to request it) Keep-Alive: timeout = 15, max = 98 Accept-Ranges: bytes Via: Moz-Cache-zlb05 Connection: Keep-Alive X-Cache-Info: caching X-Cache-Info: caching Content-Length: 325 (The content contains a standard page that will be shown if the client is unable to follow the link) 301 Moved Permanently

    Moved Permanently

    The document has moved here.


    Apache / 2.2.3 (Red Hat) Server at Port 80 site

    The message that the requested resource does not exist: