• Borovsky index php user. Sessions in PHP. Database Schema

    From the very beginning, PHP was accepted with a bang, but as soon as large enough projects began to be created in this language, developers faced a new problem - there was no concept of global variables in PHP! That is, a certain script was executed, sent the generated page to the client, and all the resources used by this script were destroyed. Let me try to illustrate: suppose there are two pages of the same site, index.php and dothings.php. The source code for these pages looks like this:

    index.php dothings.php

    If we execute these two scripts, then on the first page we will see the inscription "I was asked to index.php", and the second page will be empty.

    Website developers, without thinking twice, began to use cookies to store global variables on the client side. The process looked something like this: a user comes to the main page of the site, performs some actions, and all information related to this user, which may be required on other pages of the site, will be stored in his browser in the form of a cookie. This method has quite serious drawbacks, due to which many developers turned their backs on PHP at one time. For example, we need to authorize a user to allow him access to private (or owned only by him) sections of the site. You will have to send a cookie to the user, which will serve as his subsequent identifier on the site. This approach becomes very cumbersome and inconvenient as soon as the site begins to collect more and more information about the user's behavior, because it is desirable to encode all the information sent to the user so that it cannot be faked. More recently, a fake cookie could "put" more than one chat, and sometimes even get into someone else's mail. In addition, there are still strange people in the world whose browser does not support cookies.

    I will not go into the technological issues of the session mechanism, but will only describe how to properly work with sessions in PHP.

    How to work with sessions?

    If you test the examples from the article (or your scripts) on some commercial hosting, there should be no problems with working with sessions. If you set up your server yourself (whether it be a real server or an emulator), errors like this may appear:

    "Warning: open(/var/state/php/sess_6f71d1dbb52fa88481e752af7f384db0, O_RDWR) failed: No such file or directory (2)".

    It just means that you have PHP configured incorrectly. You can solve this problem by setting the correct path (to the existing directory) for saving sessions in the php.ini file and restarting the server.

    Any script that will use variables (data) from sessions must contain the following line:

    session_start();

    This command tells the server that this page needs all the variables that are associated with this user (browser). The server takes these variables from the file and makes them available. It is very important to open a session before any data is sent to the user; in practice, this means that it is desirable to call the session_start () function at the very beginning of the page, like this:

    session_start(); ?> ... To set the directory in which session files will be saved, use the session_save_path() function: session_save_path($_SERVER["DOCUMENT_ROOT"]."/session"); session_start();

    Once the session has started, global variables can be set. If you assign a value to any field of the $_SESSION array, a variable with the same name is automatically registered as a session variable. This array is available on all pages using the session. Let's take a program as an example:

    index.php Everything is OK. Session loaded! Let's go and see what's there: dothings.php

    When these files are run sequentially, the first "index.php" script will produce the following result:

    All OK. Session loaded! Let's go and see what's there:

    And the second "dothings.php" is this:

    I was asked for index.php

    The $a variable is now available on all pages on this site that have started sessions.

    Other useful functions and tricks for working with sessions:

    • unset($_SESSION["a"]) - session "forgets" the value of the given session variable;
    • session_destroy () - the session is destroyed (for example, if the user left the system by clicking 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 a unix_timestamp that determines the session "death" time. By default, a session lives until the client closes the browser window.
    • session_write_close () - writing session variables and closing it. This is necessary to open the site in a new window if the page is taking a long time to process and has blocked the session file for your browser.
    Examples

    Now let's turn to the practical application of the session mechanism. Here we will look at a couple of fairly simple yet useful examples.

    User Authorization

    Questions about user authorization using PHP sessions are constantly asked in web programming conferences. The mechanism for authorizing users in the system using sessions is quite good in terms of security (see section ).

    Our example will consist of three files: index.php, authorize.php and secretplace.php. The index.php file contains a form where the user will enter their username and password. This form will pass the data to the authorize.php file, which will allow the user to access the secretplace.php file if the authorization is successful, otherwise it will give an error message.

    Examples: index.php Enter password Login:
    Password:
    authorize.php You entered the wrong password! secretplace.php Hi , you're on a secret page!!! :)

    Safety

    So, we can pass an identifier from one page (PHP script) to another (until the next call from our site), which means we can distinguish between all site visitors. Since the session identifier is a very large number (128 bits), there is practically no chance that it will be possible to pick it up by brute force. Therefore, the attacker is left with the following options:

    • there is a "trojan" on the user's computer that steals session numbers;
    • the attacker captures the traffic between the user's computer and the server. Of course, there is a secure (encrypted) SSL protocol, but not everyone uses it;
    • a neighbor approached our user's computer and stole the session number.

    Such situations, based on the fact that someone steals something from someone, in general, are not within the competence of a programmer. Administrators and users themselves should take care of this.

    However, PHP can very often be "cheated". Let's look at possible hacks in the user authorization program:

    • The authorize.php file is an attempt to guess a password using a third-party script;
    • The file secretplace.php is an attempt to trick the program by entering the values ​​of the $logged_user variable in the address bar of the browser, like this:
      "http://www.yoursite.ru/secretplace.php?logged_user=hacker"

    So, in our program, two "holes" are clearly visible, one is small and not very noticeable, but the second is just huge, through which most hackers climb where they don't need to.

    How to "patch" hole number 1?

    We will not write tons of code to block an IP address, etc., but simply check where the request comes from, or rather, from which page the request came from, if it is any page from our site, then everything is fine, but in all other cases we will not let. Let's correct the authorize.php file:

    authorize.php V2 You entered the wrong password!
    How to get rid of "hole" number 2?

    Suppose you have a website where every mortal can register to post to a forum. Naturally, in the forum some users (admins, moderators) have more opportunities than others, for example, they can delete messages from other users. You store the user's access level in the session, in the $user_status variable, where $user_status = 10 corresponds to full system access. It is enough for an attacker who comes to the site to register in a regular way, and then add ?user_status=10 in the address bar of the browser. So you got a new admin on the forum!

    In principle, any script variable can be set through the address bar by simply adding a question mark after the full address to the script and the name of the variable with its value. Let's fix our code to avoid this:

    secretplace.php V2 Hi , you're on a secret page! Results

    The session mechanism is a pretty neat feature of the PHP language. Sessions are simple, very flexible in use. By the way, there is one, little documented feature of PHP sessions (available starting from version 4.0.3) - sessions can store not only variables, but also objects.

    Examples ?>
    // Automatic insertion of SIDs into links. ini_set("session.use_trans_sid", true); session_start(); ?> Click here!
    Click here!!

    // An example of working with sessions. session_start(); // If the site has just been visited, reset the counter. if (!isset($_SESSION["count"])) $_SESSION["count"] = 0; // Increment counter in session. $_SESSION["count"] = $_SESSION["count"] + 1; ?> Count of times(s).
    Close the browser to reset the counter.