Good day! How to store sessions using standard PHP or database? I often notice that in the cms session is stored in the database. What situations to use storage in the database? And what are the pros and cons of this? If anyone has a link to an article where the two methods are compared in detail, discard it. Thank you so much.

    3 answers 3

    If to compare storage in a DB and in file system ...

    The pluses seen by me:

    • Simplification of cleaning due to the use of indexes (as a rule, relational or document-oriented databases) or automatic cleaning of keys (as a rule, key-value databases).
    • If the relational database is the possibility of connections of other entities with sessions. The session was closed, the row was removed - due to ON DELETE CASCADE , the related objects were also automatically cleared.
    • Greater security for shared-hosting, where, in case of incorrect configuration of the server, you can access files with session data, or at least list their names (identifiers).
    • If the serialization is self-made or in a common format, then it is possible to divide sessions between several subsystems, including those implemented in different languages ​​and technologies.

    Visible by me cons:

    • Depending on the database, the speed of working with sessions can be much slower, slowing down the loading of pages. For example, in PostgreSQL, I would only put sessions on a seriously grounded need. If the database makes some guarantees of reliable storage, then perhaps it only spends the extra time.
    • Low-useful information in the database can lead to its excessive growth. Sessions do not live very long - the data are, in fact, ephemeral. For example, with an in-memory database (for example, MemcacheDB, Redis) on a small number of active visitors who do not want to accept cookies (robots fit well), it is easy to use quite a lot of memory. To achieve defragmentation and release-return it back to the system may not be the easiest task.

      Your question, alas, too, how to say it ..... private. I, for example, in one of the projects kept the sessions in the database solely in order to make it easier to track the number of users online and as a "tool" for autologin. In other cases, I managed without it. A special case.

        One of the advantages of storing a session in the database is scalability. Another speed slightly increases (page generation speed). Yes, and paranoid this topic is not spared, "safer" after all.