Connection session. HTTP session


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

  1. The client establishes a TCP connection (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 a status code and relevant data.

Since HTTP/1.1, the connection is not closed after the third phase 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, the default HTTP server port on a computer is port 80, although others are also commonly used, such as 8000 or 8080. The URL of the page to load contains the domain name and port, which can be omitted as long as it matches the default port.

We mean: The client-server model does not allow the server to send data to the client without explicitly requesting that data. To get 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 client request

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

  1. The first lines contain the request method and its parameters:
    • path to the document - absolute URL without specifying the protocol and domain name
    • HTTP protocol version
  2. Each subsequent line is an HTTP header and conveys to the server some information about the types of data it prefers (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.

Example requests

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

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

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

We send the result of form submission:

POST /contact_form.php HTTP/1.1 Host: website 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 a resource. Although they can also be nouns, these request methods are sometimes called HTTP commands. The most common GET and POST requests are:

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

Structure of the response from the server

After the connected 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 is the status line, consisting of confirmation of the HTTP version used and the status of the request (and its meaning in a human-readable form).
  2. The following lines are HTTP headers that give the client some information about the data being sent (eg type, size, compression algorithm, caching hints). Just like in the case of a client request, these HTTP headers form a block ending with an empty line.
  3. The last block contains the data (if any).

Sample answers

Successfully received web page:

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 comes 29769 bytes of the requested web page)

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 cannot follow the link) 301 Moved Permanently

Moved Permanently

The document has moved here.


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

Message that the requested resource does not exist:

The web server does not maintain a permanent connection with the client, and each request is processed as a new one, 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. It was to solve these two problems that sessions were invented.
Actually, sessions, in a nutshell, are a mechanism that allows you to uniquely identify a browser and creates a file for this browser on the server in which session variables are stored.

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

In principle, it’s quite easy 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 to see if a cookie with a specific name was received. 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 the data from the database. With another 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 one is enabled, then at the start of the session (each time session_start() is called) a cookie is set for the client. The browser correctly returns this cookie with each subsequent request and PHP has a session identifier. 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 one is enabled, then the cookie is not set. And this is what happens, for the sake of which, in fact, it is worth using the built-in session mechanism. After the script does its job and the page is completely formed, PHP scans the entire page and adds a session identifier 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 identifier is only added to relative links.

Theoretically, in our homemade sessions on cookies and the database, we can manually assign ID transfer to all links - and then our own sessions will work regardless of cookies. But would you agree - it’s more pleasant when someone else does this work? ;-)

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

Phew. The ID transfer is complete.
Now all that remains is to bind the data file to it on the server side.
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 note here.
The $_SESSION array is special.
In fact, it contains the variables that we want to make available in various scripts.
To place a variable in a session, just assign it to the $_SESSION array element.
To get its value, just access the same element. An example will be below.

PHP also handles garbage collection - removing outdated files. As well as data encoding and a bunch of other necessary things. As a result of this care, working with sessions is very simple.
Here we actually come to the example of how sessions work.
A very small example:
session_start();

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

We check whether we have a counter variable in the session; if not, then we create it with the value 0, and then display 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 EVERY file in which we need sessions:
session_start();
And then access 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 produces when trying to work with sessions are the following:
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 thread
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 to the directory specified in php.ini where session files are written is not available. This error is the easiest to fix. Just register a directory that exists and is writable, for example,
session.save_path = c:\windows\temp
And don't forget to restart Apache after this.

As it turns out, human intelligence has no limits, and therefore I am forced to explain:
a message about the third error (the directory cannot be found) will INEVITABLY lead to the appearance of the first two, since the error message is output to the browser and headers after it cannot be used. Therefore, do not rush to look for a premature conclusion, but first write down the right path!

The next most common problem when working with sessions is the heavy legacy of register_globals. DO NOT give script variables names that match the indices of the $_SESSION array!
With register_globals=on the values ​​will overwrite each other and you will 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.”, if the script has a session variable that has no value, and a global variable with the same name . To get rid of it, you must always initialize variables before use (or at least check for existence) and do not give global variables names that coincide with the indexes of the $_SESSION array.

If it doesn’t work, but no messages are displayed, then add two lines at the very beginning of the script responsible for displaying ALL errors on the screen - it’s 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 at least see them. You can read a little more about finding errors in this section.

If you are sure that there are no errors, but the example given does not work anyway, then perhaps PHP does not enable passing id via URL, and cookies for some reason do not work.
Look what's wrong with your cookies.
In general, if your sessions are not working, then first try passing the session identifier manually, that is, make a link and assign an identifier to it:
session_start();
if (!isset($_SESSION["counter"])) $_SESSION["counter"]=0;
echo "You updated this page ".$_SESSION["counter"]++." times.

update";
?>

However, you should make sure that the session.use_only_cookies directive is not enabled, which prevents PHP from accepting the session ID if it was passed via URL

If this example does not work, then the problem is either in trivial typos(half of the “problems” with sessions come from a misspelled variable name), or in a too old version of PHP: support for sessions 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. Monitor what kind of cookie the server sets to the browser, and whether the browser returns it. It is very useful to search by looking at the exchange of HTTP headers between the browser and the server.
An explanation of how cookies work is beyond the scope of this already too long text, but at least make sure that the server sends a cookie with an identifier, and the browser returns it. And at the same time 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 the 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 cookies other than the session ID.

If the browser does not return cookies, check whether the cookies work at all.
Make sure that the domain you are accessing has a normal name (with at least one dot and no illegal 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 doesn't, 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, and debug your script.

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

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

Safety
Session security is a broad topic. Therefore, I will focus on a few main points.
The most textbook one 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 in addition to 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, which allows you to set your own directory for saving session files. This is more secure than having them 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 using a script that checks authorization, Internet Explorer refuses to download it. It's because of this title. Call
    session_cache_limiter("private");
    must solve the problem before starting the session.
  • Strange as it may seem, you cannot use numeric indexes in the $_SESSION array - $_SESSION, $_SESSION["10"] - sessions will not work.
  • Somewhere between versions 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.
  • Before version 4.3.3 of the cookie, PHP sent a cookie only if there was no identifier in the request when the session started. Now the cookie is sent every time session_start() is called

    Example of authorization using sessions
    Let's illustrate all of the above with a small example:
    Let's create the 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 all you need to do is write the line in all protected scripts
    require "auth.php";
    This example assumes that the session has already started and a connection to the database has been created using the Class for safe and convenient work with MySQL. It also assumes that the password is hashed using the recommended password_hash function.
    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 latest and most recent information about session support in PHP in the official documentation, plus numerous user comments. Highly recommended reading.
    http://phpclub.ru/manrus/f/ref.session.html - A VERY outdated translation of this chapter into Russian, from the documentation translated by Alexander Pyramidin.
    http://phpclub.ru/detail/article/sessions
    An article with the pathetic title “The Truth about Sessions.” Leaves an ambivalent impression. At the beginning, the author talks VERY clearly about the session mechanism, but the methods he offers by the end of the article are completely unclear.

    A textbook article by Dmitry Borodin from the site
    http://php.spb.ru/ is strongly NOT recommended.
    Guys, it's terribly outdated. Not only does it contain factual inaccuracies, but sessions in PHP have simply not been worked with for a long time.
    Many thanks to Dima for it, this was the first article on the sessions in Russian, I studied from it myself, but now I need to send it to a well-deserved rest.
    Unfortunately, many other articles on the Internet that have not been updated for years are also outdated.


  • Sessions in PHP or as data about a user or customer who visits a site are saved when moving between pages of a site without much difficulty. The lesson is very important. Relevant for creating 95% of websites.

    What is a session in php

    Sessions are used to store temporary data (for example, that a user has visited a site) when navigating between pages of the same site. When using sessions, data is stored in temporary files on the server.
    Most often, sessions (and cookies, too) are used when creating online stores, forums, message boards, social networks, blogs and other resources. The convenience of the session system is to store temporary information of the logged in user/customer, data about which is quickly accessible 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, data about the user/customer will still be available.

    Session logic

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

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

    File index.php

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

    $login = "admin";
    $password = "pass";
    $_SESSION["login"] = $login; // save a variable containing login
    $_SESSION["password"] = $password; // save a 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 any data on this page!
    See, it's simple!

    4. If you want to clear session data, then all you need to do is:

    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

    Session_destroy(); // destroy the session. All data, including $_SESSION["password"] is no longer there. When requesting them, 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. I repeat, sessions should contain small amounts of data, so they are suitable for storing login/password, shopping cart and other small volumes.

    Passing a value or array using a PHP session

    You can write not only a string, but also an array of data to a session. Just don’t overdo it with the volume of the array, as all this will affect the speed and occupied space on the server.

    We again use a certain start page index.php

    Session_start();

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

    $_SESSION["arr"] = $r;

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

    Destination file, page test.php where we open the array

    Session_start();
    print_r($_SESSION["arr"]);
    // will print
    /*
    Array
    => one
    => two
    => three
    */
    ?>
    You might want to brush up on the lesson 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 left the system by clicking the exit button);
    session_set_cookie_params(int lifetime [, string path [, string domain]])- using this function you can set how long a session will live by setting a unix_timestamp that determines the time of death of the session.

    List of functions for working with sessions in php
    session_cache_expire - returns the expiration of the current cache
    session_cache_limiter - Gets and/or sets the current cache limiter
    session_commit is an alias for session_write_close()
    session_decode - decodes session data from a string
    session_destroy - destroys all data registered for the session
    session_encode - encrypts the current session data as a string
    session_get_cookie_params - gets session cookie parameters
    session_id - gets and/or sets the current session id
    session_is_registered - determines whether the variable is registered in the session
    session_module_name - gets and/or sets the current session module
    session_name - gets and/or sets the name of the current session
    session_regenerate_id - modifies the current session id with a 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

    Examples of session work

    Counter of page views during a session. A clear example of work. However, after closing the browser, the countdown will begin again.

    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


    You have opened this page in your current browser session
    time(s).
    Close your browser to reset this counter.
    Click here to update the page!
    With each transition the counter will increase by 1)

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





    

    2024 gtavrl.ru.