Answer the question
In order to leave comments, you need to log in
How to make sessions and authorization in PHP?
Beginner coder, please don't pick on too much.
PHP 7.0.4 + MySQL 5.7 + PhpStorm 2016.1.2 + XDebug 2.4.0 I
wanted to write my own CMS. Made a frame, it's time to teach her to distinguish between users. I have been reading various topics with pitfalls, etc., all of which were written more than 2 years ago.
There are 2 options in mind:
1. Session + database. We set the lifetime of the session to a week and do not worry. We write session_id, user_id, user_agent, session_expire to the sessions table of the database and check / update them with each request, except for AJAX-like ones, although it is possible for them.
2. Cookies + database. Upon successful authorization, we create a user_id, random_hash, user_agent, expire record in the sessions table of the database. In cookies we write user_id, random_hash. Cookies are valid for a week, when visiting we check and renew cookies for another week. Essentially the same, just change $_SESSION to $_COOKIE.
"random_hash" is just a random set of letters replacing the session_id in the first example. A sort of temporary password, IMHO safer than the user's password hash.
When changing the password or at the request of the user, all his sessions are deleted from the database and all cookies / sessions will become invalid.
For now, I'm looking at the first option.
And yet, how to deal with unauthorized users? Also create sessions for them? Nevertheless, they also have access rights and they can be compared with registered ones.
Answer the question
In order to leave comments, you need to log in
Both approaches are not very good, as they mix user authentication logic with event logging logic. Conventionally, you have 3 models: User, Session and UserLog.
Communication between UserLog and Session mediated through User. This approach will allow you to a) organize the storage of sessions in the form of "1 user - 1 cookie", b) even if the user's cookie has died and a new one has been issued to him, you save the user's history, because UserLog is tied to User through a foreign key.
Зачем вообще сессию в БД хранить?
Авторизовался юзер - старт сессии. Браузер закрыл / открыл / время истекло - ещё раз авторизовался.
Всё равно многие пароли в браузерах сохраняют.
сделайте абстракцию над сессиями который будет использовать драйвер. Драйвера будут реализовать к примеру хранение сессий в редисе и в файловой системе. И потом пользователь сам настроит что хочет.
В БД для таблицы юзеров добавляешь, например auth_token, при входе его генерируешь и пишешь в куку. При заходе пользователя с кукой, в которой есть нужный токен - логинишь под нужным юзверем.
Самый простой вариант.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question