L
L
Li2020-05-09 22:39:40
PHP
Li, 2020-05-09 22:39:40

How to correctly recognize an authorized user?

The user is successfully authorized. After that, it must be remembered.

Always used the option:
Generated a hash. Saved it in cookies and db. Match = Authorized.

But there is also an option with sessions.

Please share your experience, which option is preferable, and is it possible, in the case of sessions, to save the user, for example, for a month?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
granty, 2020-05-10
@cubaPro

A session in PHP is practically the same as your "cookies + database", only the session file is used instead of the database. It will be different for each user.
A unique hash (session ID) is generated, it is placed in a cookie for the user, and a file with the name == session ID is created on the server. PHP does it all by itself.
The session file (on the server) stores all the variables you want. When a session is raised, PHP will automatically initialize the $_SESSION array
with your variables (Username, user IP, last login date, user permissions, etc.).
There are built-in functions for working with sessions in PHP, they do not all work in an obvious way, but you can figure it out.
PS: If cookies are not supported, then the session ID can be passed as a parameter in the URL.

Is it possible in the case of sessions to save the user, for example, for a month?
Yes. Set a session cookie to have a lifetime of 1 month, and after a month the user's browser will automatically destroy it. After that, you will need to log in again.
But on the server, there is a PHP settings parameter session.gc_maxlifetime , which sets the lifetime of a PHP session on the server. After session.gc_maxlifetime expires, PHP garbage collection deletes the session file on the server. That is, it should be set > month.
which option is preferable
holly question. If there is a need to monitor users (who logged in and when and what they did) - using the database it is more convenient than rummaging through a thousand files with your hands.
In terms of security - the same, maybe the same mechanism works. Cookie hijacking -> session spoofing.
PS: There is a good article on Habré Pitfalls of using sessions in PHP .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question