When programming in PHP, I have a habit of not using ready-made library files, such as PHPLib or other similar libraries. In this system, I also plan to write a library file myself, which Need to handle authentication, email confirmation, account update (password, email) and other matters.
In order to ensure the security of the system without increasing the burden on my existing database. Therefore this new system relies on cookies. This is indeed a dilemma, because it is very unsafe to just set a cookie with a user name. This will not work, but considering the burden on the database, I cannot add a simple unordered code and hand it over to my database for verification.
The solution is to set two cookies at the same time, one is the user name cookie, and the other is the unordered cookie. This unordered code is actually generated by a combination of the username and a super password (known only to the programmer) through the md5() function operation. Since md5() is a one-way disordered code, it cannot be cracked. When the user changes their email, I can also use the email and super password to generate a random code to allow the user to confirm the change. This is actually a public key/private key type system. not understand? It doesn't matter, I will explain it slowly below.
Interestingly, the scalability of this system can reach infinite, because the main work of the system is to calculate the value of the md5() function, and it is completed by the web server. When the load increases, other servers can be added to share the load. Although the authentication system does not drag across a database, doing so makes the final bottleneck only appear in the database.
The following are two functions in this library - token generation and token authentication functions.
$hidden_hash_var='your_secret_password_here';
$LOGGED_IN=false;
unset($LOGGED_IN);
function user_isloggedin() {
global $user_name,$id_hash,$hidden_hash_var,$LOGGED_IN;
File://Has the disorder code been detected?
file://If yes, return the variable
if ( isset($LOGGED_IN) ) {
Return $LOGGED_IN;
}
file://are both cookies present?
if ($user_name && $id_hash) {
/*
A random code for authentication is generated from the user name and system super password obtained from cookies. If the random code is the same as the random code in the cookie, then the variables in the cookies are credible and the user has logged in
*/
$hash=md5($user_name.$hidden_hash_var);
if ($hash == $id_hash) {
File:// unordered code matches, set a global variable, so that when we call the function again,
file://, there is no need to perform the md5() operation again
$LOGGED_IN=true;
return true;
} else {
file://The two disorder codes do not match and there is no login
$LOGGED_IN=false;
return false;
}
} else {
$LOGGED_IN=false;
return false;
}
}
function user_set_tokens($user_name_in) {
/*
Once the username and password are verified, call this function