The principle and example of PHP cookie recording login information

Source: Internet
Author: User
Tags session id php session set cookie setcookie

That's probably what I did:

(1) Generate user authentication token
After the user logs in I will generate a token that token may consist of the following information: Username+ip+expiration+salt "Just an example", then encrypt the composition information to the token with a reversible cryptographic function and save the token to the database. Write cookies;

(2) The last way to check the information to determine the user's login status
Decrypt the token, verify that the user username, if present, continue, and then verify that token is the same as the token in the database, if the same continues; Verify that the validity of the cookie is expiration, if it is valid to continue, verify that the IP is changing, and if the change jumps into the login ... You can even verify the user agent.

Example

PHP Session Application Instance--Login authentication:

The code is as follows Copy Code

<title>Login</title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

<body>
<form name= "Form1" method= "Post" action= "login.php" >
<table width= "border=" 0 "align=" center "cellpadding=" 2 "cellspacing=" 2 ">
<tr>
&LT;TD width= "><div" align= "right" > Username:</div></td>
&LT;TD width= "><input" type= "text" name= "username" ></td>
</tr>
<tr>
<td><div align= "Right" > Password:</div></td>
<td><input type= "password" name= "passcode" ></td>
</tr>
<tr>
<td><div align= "Right" >cookie save time:</div></td>
<td><select name= "Cookie" id= "Cookie" >
<option value= "0" selected> Browser process </option>
<option value= "1" > Save 1 days </option>
<option value= "2" > Save 30 days </option>
<option value= "3" > Save 365 days </option>
</select></td>
</tr>
</table>
<p align= "center" >
<input type= "Submit" name= "submit" value= "Submit" >
<input type= "reset" name= "reset" value= "reset" >
</p>
</form>
</body>

--------------------------------------------------------------------------------------------------------------- ----------

<?php
@mysql_connect ("localhost", "root", "1981427")//Select database before you need to connect to the database server
Or Die ("Database server Connection Failed");
@mysql_select_db ("test")//Select Database MyDB
Or Die ("database does not exist or not available");
Get user input
$username = $_post[' username '];
$passcode = $_post[' passcode '];
Execute SQL statement to get the value of the session
$query = @mysql_query ("Select Username, userflag from users"
." where username = ' $username ' and passcode = ' $passcode ')
Or Die ("SQL statement execution failed");
Determine if the user exists and the password is correct
if ($row = mysql_fetch_array ($query))
{
Session_Start (); Mark the beginning of the session
Determines whether the user's permission information is valid, or if 1 or 0 is valid
if ($row [' userflag '] = = 1 or $row [' userflag '] = = 0)
{
$_session[' username ' = $row [' username '];
$_session[' userflag ' = $row [' Userflag '];
echo "<a href=" main.php "mce_href=" main.php "> Welcome to login, click here to enter the Welcome interface </a>";
}
else//If the permission information is invalid output error message
{
echo "User right information is incorrect";
}
}
else//If the username and password are incorrect, the output error
{
echo "User name or password error";
}
?>

--------------------------------------------------------------------------------------------------------------- ----------

<?php

Session_Start ();
unset ($_session[' username '));
unset ($_session[' passcode '));
unset ($_session[' Userflag '));

Finally completely destroy session.
Session_destroy ();

echo "Logout success";
?>

<?php
Initializes the session.
Session_Start ();
/*** Delete all Session variables ... Unset ($_session[xxx]) can also be deleted individually. ****/
$_session = Array ();
/*** deletes the Sessin ID. Because the session defaults to cookies, use Setcookie to delete the cookie.***/that contains the session ID
if (Isset ($_cookie[session_name ())) {
Setcookie (Session_name (), ', Time ()-42000, '/');
}
Finally completely destroy session.
Session_destroy ();
?>

From this we can draw the step of deleting the session:
①session_start ()
②$_session=array ()/unset ($_session[' xxx ')
③session_destroy ()

--------------------------------------------------------------------------------------------------------------- ----------


<?php
Session_Start ();
if (isset ($_session[' username '))
{
@mysql_connect ("localhost", "root", "1981427")//Select database before you need to connect to the database server
Or Die ("Database server Connection Failed");
@mysql_select_db ("test")//Select Database MyDB
Or Die ("database does not exist or not available");
Get session
$username = $_session[' username '];
Execute SQL statement to get Userflag value
$query = @mysql_query ("Select Userflag from Users"
." where username = ' $username ')
Or Die ("SQL statement execution failed");
$row = Mysql_fetch_array ($query);
The information in the current database is judged by comparison with the message in the session, and the session information is updated if different.
if ($row [' Userflag ']!= $_session[' Userflag '])
{
$_session[' userflag ' = $row [' Userflag '];
}
Output different welcome information according to the session value
if ($_session[' userflag '] = = 1)
echo "Welcome admin". $_session[' username '. " Login System ";
if ($_session[' userflag '] = = 0)
echo "Welcome user". $_session[' username '. " Login System ";
echo "<a href=" logout.php "mce_href=" logout.php "> Logoff </a>";
}
Else
{
echo "You do not have permission to access this page";
}
?>

--------------------------------------------------------------------------------------------------------------- ----------

-------------------------------------------------------------Cookie Logon Authentication instance---------------------------------------------


<title>Login</title>
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 ">

<body>
<form name= "Form1" method= "Post" action= "login.php" >
<table width= "border=" 0 "align=" center "cellpadding=" 2 "cellspacing=" 2 ">
<tr>
&LT;TD width= "><div" align= "right" > Username:</div></td>
&LT;TD width= "><input" type= "text" name= "username" ></td>
</tr>
<tr>
<td><div align= "Right" > Password:</div></td>
<td><input type= "password" name= "passcode" ></td>
</tr>
<tr>
<td><div align= "Right" >cookie save time:</div></td>
<td><select name= "Cookie" id= "Cookie" >
<option value= "0" selected> Browser process </option>
<option value= "1" > Save 1 days </option>
<option value= "2" > Save 30 days </option>
<option value= "3" > Save 365 days </option>
</select></td>
</tr>
</table>
<p align= "center" >
<input type= "Submit" name= "submit" value= "Submit" >
<input type= "reset" name= "reset" value= "reset" >
</p>
</form>
</body>

--------------------------------------------------------------------------------------------------------------- ----------

<?php
@mysql_connect ("localhost", "root", "1981427")//Select database before you need to connect to the database server
Or Die ("Database server Connection Failed");
@mysql_select_db ("test")//Select Database MyDB
Or Die ("database does not exist or not available");
Get user input
$username = $_post[' username '];
$passcode = $_post[' passcode '];
$cookie = $_post[' Cookie '];
Execute SQL statement
$query = @mysql_query ("Select Username, userflag from users"
." where username = ' $username ' and passcode = ' $passcode ')
Or Die ("SQL statement execution failed");
Determine if the user exists and the password is correct
if ($row = mysql_fetch_array ($query))
{
if ($row [' userflag '] = = 1 or $row [' userflag '] = = 0)//Determine whether the user rights information is valid
{
Switch ($cookie)//Set cookie save time based on user's choice
{
Case 0://Save cookie for browser process
Setcookie ("username", $row [' username ']);
Break
Case 1://Save 1 days
Setcookie ("username", $row [' username '], time () +24*60*60);
Break
Case 2://Save 30 days
Setcookie ("username", $row [' username '], time () +30*24*60*60);
Break
Case 3://Save 365 Days
Setcookie ("username", $row [' username '], time () +365*24*60*60);
Break
}
Header ("location:main.php"); Auto Jump to main.php
}
Else
{
echo "User right information is incorrect";
}
}
Else
{
echo "User name or password error";
}
?>

--------------------------------------------------------------------------------------------------------------- ----------

<?php
Session_Start ();
if (isset ($_cookie[' username '))
{
@mysql_connect ("localhost", "root", " 1981427 ")     //Select database before you need to connect to the database server
or Die (" Database server Connection Failed ");
@mysql_select_db (" test ")      //Select database MyDB
or Die ("database does not exist or unavailable");
//Get session
$username = $_cookie[' Username '];
//Execute SQL statement get Userflag value
$query = @mysql_query (select Userflag from Users
.) where username = ' $username ')
or Die ("SQL statement execution failed");
$row = Mysql_fetch_array ($query);
//Get user rights information
$flag = $ row[' Userflag '];
//Output different welcome information according to the value of Userflag
if ($flag = = 1)
echo "Welcome administrator". $_cookie[' username '. " Login System ";
if ($flag = = 0)
echo "Welcome user". $_cookie[' username '. " Login System ";
echo "<a href=" logout.php "mce_href=" logout.php "> Logoff </a>";
}
Else
{
echo "You do not have permission to access this page";
}
?

--------------------------------------------------------------------------------------------------------------- ----------

<?php
Setcookie ("username");
echo "Logout success";
?>


Final Note:

1. The above guarantee that token each login will be different, this time leading to the previous token "both cookies" invalid

2.cookie is best valid for less than a week

3. Save the User ID and a password in the client cookies (rules only I know)

4. If the program detects the client's stored cookie ID. To verify with the database password, if consistent, return the corresponding user login information, otherwise return false

It's not good to feel efficient or safe.

1. Users visit each page to verify with the database
2. Although the rule is very complex, save on the client still exists the possibility of being cracked

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.