Home
Backend Development
PHP Tutorial
Implementation code for using cookies to save user login information in PHP_PHP Tutorial



Implementation code for using cookies to save user login information in PHP_PHP Tutorial
cookie
php
code
use
keep
information
accomplish
user
Log in
of
page
Use cookies to save page login information
1. Database connection configuration page: connectvars.php
Copy code The code is as follows:
//Database location
define('DB_HOST', 'localhost');
//User name
define('DB_USER', 'root') ;
//Password
define('DB_PASSWORD', '19900101');
//Database name
define('DB_NAME','test') ;
?>
2. Login page: logIn.php
Copy code The code is as follows:
php
//Insert relevant information about connecting to the database
require_once 'connectvars.php';
$error_msg = "";
//Determine whether the user has set a cookie, if not $ _COOKIE['user_id'], execute the following code
if(!isset($_COOKIE['user_id'])){
if(isset($_POST['submit'])){//Determine the user Whether to submit the login form, if so, execute the following code
$dbc = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME);
$user_username = mysqli_real_escape_string($dbc,trim($_POST['username'])) ;
$user_password = mysqli_real_escape_string($dbc,trim($_POST['password']));
if(!empty($user_username)&&!empty($user_password)){
//The SHA() function in MySql is used to perform one-way encryption of strings
$query = "SELECT user_id, username FROM mismatch_user WHERE username = '$user_username' AND "."password = SHA('$user_password' )";
//Query with username and password
$data = mysqli_query($dbc,$query);
//If the found record is exactly one, set COOKIE and proceed to the page at the same time Redirect
if(mysqli_num_rows($data)==1){
$row = mysqli_fetch_array($data);
setcookie('user_id',$row['user_id']);
setcookie('username',$row['username']);
$home_url = 'loged.php';
header('Location: '.$home_url);
}else{//if If the found record is incorrect, set the error message
$error_msg = 'Sorry, you must enter a valid username and password to log in.';
}
}else{
$error_msg = ' Sorry, you must enter a valid username and password to log in.';
}
}
}else{//If the user is already logged in, jump directly to the logged in page
$home_url = 'loged.php';
header('Location: '.$home_url);
}
?>
< title>Mismatch - Log In
< ;body> Username and password -->
if(empty($_COOKIE['user_id'])){
echo '
'.$error_msg .'
';?>
}
?>