How to use both session and Cookie in PHP to save user login information _php tips

Source: Internet
Author: User
Tags setcookie
Use session and cookies to save user login information at the same time
1. Database Connection Configuration page: connectvars.php
Copy Code code as follows:

<?php
Location of the database
Define (' Db_host ', ' 127.0.0.1 ');
User name
Define (' Db_user ', ' root ');
Password
Define (' Db_password ', ' 19900101 ');
Database name
Define (' db_name ', ' test ');
?>

2, login page: login.php
Copy Code code as follows:

<?php
Insert information about the connection database
Require_once ' connectvars.php ';
Open a session
Session_Start ();
$error _msg = "";
If the user is not logged in, that is, if $_session[' user_id ' is not set, execute the following code
if (!isset ($_session[' user_id ')) {
if (Isset ($_post[' submit ')) {//When the user submits the login form, 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 for one-way encryption of strings
$query = "Select user_id, username from mismatch_user WHERE username = ' $user _username ' and". " Password = SHA (' $user _password ') ";
$data = Mysqli_query ($dbc, $query);
Query with username and password, if the record is exactly one, set session and cookie, and page redirection
if (Mysqli_num_rows ($data) ==1) {
$row = Mysqli_fetch_array ($data);
$_session[' user_id ']= $row [' user_id '];
$_session[' username ']= $row [' username '];
Setcookie (' user_id ', $row [' user_id '],time () + (60*60*24*30));
Setcookie (' username ', $row [' username '],time () + (60*60*24*30));
$home _url = ' loged.php ';
Header (' Location: '. $home _url);
}else{//If the record is not correct, set the error message
$error _msg = ' Sorry, must enter a valid username and password to log in. '
}
}else{
$error _msg = ' Sorry, must enter a valid username and password to log in. '
}
}
}else{//If the user is logged in, jump directly to the already logged on page
$home _url = ' loged.php ';
Header (' Location: '. $home _url);
}
?>
<title>mismatch-log in</title>
<link rel= "stylesheet" type= "Text/css" href= "Style.css"/>
<body>
<!--by $_session[' user_id '], if the user is not logged in, then display the login form, let the user enter a username and password-->
<?php
if (!isset ($_session[' user_id ')) {
Echo ' <p class= ' Error > '. $error _msg. ' </p> ';
?>
<!--$_server[' Php_self '] invokes its own PHP file when submitting a form on behalf of a user-->
<form method = "Post" action= "<?php echo $_server[' php_self '];? > ">
<fieldset>
<legend>log in</legend>
<label for= "username" >Username:</label>
<input type= "text" id= "username" name= "username"
Value= "<?php if (!empty ($user _username)) echo $user _username;?>"/>
<br/>
<label for= "Password" >Password:</label>
<input type= "password" id= "password" name= "password"/>
</fieldset>
<input type= "Submit" value= "Log in" name= "Submit"/>
</form>
<?php
}
?>
</body>

Effect Chart:



3, login page: loged.php

Copy Code code as follows:

<?php
You must open a session before you can use a variable value stored within a session
Session_Start ();
If the session is not set, see if the cookie is set
if (!isset ($_session[' user_id ')) {
if (Isset ($_cookie[' user_id ')) &&isset ($_cookie[' username ')) {
Assign a value to a session with a cookie
$_session[' user_id ']=$_cookie[' user_id '];
$_session[' username ']=$_cookie[' username '];
}
}
Check login status with a session variable
if (isset ($_session[' username ')) {
Echo ' You are logged as '. $_session[' username '. ' <br/> ';
Echo ' <a href= "logout.php" > Log out ('. $_session[' username '). " </a> ';
}
/** in the Logged-in page, you can take advantage of the user's session such as $_session[' username ',
* $_session[' user_id '] to query the database, you can do a lot of things.
?>

Effect Chart:

4. Logout Session and Cookie page: logout.php (redirect to lonin.php after logoff)
Copy Code code as follows:

<?php
/** both the session and the cookie page
Even when you log off, you must start a session before you can access session variables
Session_Start ();
Check login status with a session variable
if (Isset ($_session[' user_id ')) {
To clear the session variable, set the $_session Super global variable to an empty array
$_session = Array ();
If a session cookie exists, it is deleted by setting the expiration time to 1 hours before
if (Isset ($_cookie[session_name ())) {
Setcookie (Session_name (), ", Time ()-3600);
}
To invoke the undo session using the built-in Session_destroy () function
Session_destroy ();
}
Also set the expiration time of each cookie to a time in the past, so that they are deleted by the system, in seconds
Setcookie (' user_id ', ', ', Time ()-3600);
Setcookie (' username ', ', ', Time ()-3600);
Location header redirects the browser to another page
$home _url = ' login.php ';
Header (' Location: '. $home _url);
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.