Session is a very important thing in php. For example, our users generally use session to log in. Compared with cookies, session is much safer. At the same time, our property cart often uses session for temporary record saving. .
session_unregister() Unregister a single session variable
unset($_SESSION['age']); used to unregister the session variable registered with $_SESSION['age']
session_unset() deletes all registered variables
session_destroy() logs out all session variables and logs out the entire session
Example:
See a complete session usage method,
Use session to save user login information
//If the user is not logged in, that is, when $_SESSION['user_id'] is not set, execute the following code
if(!isset($_SESSION['user_id'])){
If(isset($_POST['submit'])){//Execute the following code when the user submits the login form
$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 there is exactly one record found, set SESSION and redirect the page at the same time
If(mysqli_num_rows($data)==1){
$row = mysqli_fetch_array($data);
$_SESSION['user_id']=$row['user_id'];
$_SESSION['username']=$row['username'];
$home_url = 'loged.php';
header('Location: '.$home_url);
}else{//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);
}
?>
& Lt;!-Through the $ _Session ['user_id'], it is judged. If the user fails to log in, the login form is displayed so that the user enters the username and password-& gt;
If(!isset($_SESSION['user_id'])){
echo '
echo 'You are Logged as '.$_SESSION['username'].' ';
//点击“Log Out”,则转到logOut页面进行注销
echo ' Log Out('.$_SESSION['username'].')';
}
/**In the logged in page, you can use the user's session such as $_SESSION['username'],
* $_SESSION['user_id'] queries the database and can do many things*/
?>4、注销session页面:logOut.php(注销后重定向到lonIn.php)
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn