Why would you need this?
It is a security requirement to make sure actions made by an employees on a web application are originated only from a single device/system at any time. This is to make forensic job in case of incident easier.
How it should work
Not allowing a user to login from second decivce is a serious problem as it is possible that a hacker logged in to users account and then user will not be able to login anymore. It is also possible that user lost session (clear cookies) and evidence of login on server is orphaned, meaning client does not have a way of reaching their account without help of someone from server (support, server admin...)
Better solution is to invalidate previous sessions when a new login happens. This will allow recovering from expired session, change of device, or lost cookies. With this solution if a hacker log in using same username, current logged in user will know as soon as they try to complete any action, which will fail due to invalidated session.
How to implement it
You will need to create a unique login ID (ULID) during user login. A copy of ULID is stored with user session ($_SESSION) and another copy need to be stored permanently linked to username, But it cannot be stored in session or cookie since it is per device/browser (Sessions are handled by cookie).
You can store permanent copy of ULID with user record in database, or store it in a file together with username. PHP doesn't have application level variables but it is possible to use linux shmop too, however it requires a linux system and if the server restarts, all sessions will be invalidated (not desired).
For high traffic systems, a file or directory is a better choice. In case of file use something like ini file format username=ULID and in case of directory use username as filename and store hash inside the file.
every time user sends a request to server, check the hash stored in their session and compare with permanent version, if they are same, continue and if they are not, inform user that their user is just logged in from different device and this session is invalidated, and then redirect them to login screen.
Now there are two scenarios, that is:
- It is user who logged in to new device and their old session is invalid, which is fine
- A hacker just logged in using different device, since user is notified they can login and change their password or seek assistance from application support.
Note
- ULID can be even MD5 or SHA1 of a random number + time + username is enough since it is only handled on server side and client doesn't have access to it or you can use a CSRF token if you wish.
- ULID stored permanently serves no purpose when there is no sessions, since there is nothing to compare it to.
- To avoid hash collision on high traffic websites, use newer hashes such as SHA256