Home > Article > Backend Development > How to keep user logged in in php
PHP method to maintain user login status
1. Change the user information, such as ['uid'=>123, 'username The array of '=>'testuser'] is serialized into a string. The string is encrypted using a reversible encryption algorithm and written to a COOKIE with the key userinfo.
2. Since the reversible encryption algorithm is easy to decrypt, once the encryption rules are guessed by others, they can easily tamper with the content of this COOKIE, and then encrypt it according to the encryption rules and then forge it.
So, we add another infodig COOKIE, which is to add the above userinfo COOKIE content to the salt and use an irreversible encryption algorithm to generate a hash. As for the salt, we can decide it ourselves. In short, it must be kept secret from the outside. The irreversible algorithm For example, md5, or even md5 with salt multiple times.
3. For the above two COOKIES, in order to enhance security and prevent users from being obtained by XSS attacks, you can set the http-only attribute.
After the server determines that the above two COOKIES exist
1. Verify whether infodig and userinfo match (after calculating the content of userinfo using the method of generating infodig, and COOKIE Does the uploaded infodig match?
2. After the infodig verification is passed, use the decryption algorithm to decrypt the userinfo string to obtain the user information. If the uid in the user information exists in the user table, write SESSION and keep it through SESSION. Summary of this session
:
It is feasible to use COOKIE to record user information (of course it is not recommended to store user-sensitive things in COOKIE, such as email, mobile phone, and even passwords , only record the parts that are useful for login, such as uid, username and other identifiers, and nickname may improve the user experience in some places). What is certain is that this COOKIE is visible to the user. What we have to do is two things:
1. Try to make it incomprehensible to users, and only our server knows it (reversible encryption algorithm)
2. Even if the user understands it, he cannot easily forge it (irreversible encryption algorithm) Column algorithm)
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to keep user logged in in php. For more information, please follow other related articles on the PHP Chinese website!