Home  >  Article  >  Backend Development  >  PHP user login code session, cookie automatic memory function_PHP tutorial

PHP user login code session, cookie automatic memory function_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 16:59:471104browse

When users log in, there are many basic user logins like my example. Running to the specified page is not safe. If the user knows your address, there is no need to log in. Example 2 uses session, which is also more commonly used in operations. The page has added session verification, but cannot remember the next login. Example 3 uses session and cookie to log in simultaneously and can automatically record the next automatic login function.

Let’s look at the simplest example first

Attached below is the simple login.htm content

The code is as follows Copy code
 代码如下 复制代码




用户名

密码








Username

Password





login.php content is as follows:
 代码如下 复制代码

error_reporting(0);
$mysql_servername = "localhost"; //主机地址
$mysql_username = "root"; //数据库用户名
$mysql_password =""; //数据库密码
$mysql_database ="peng"; //数据库
mysql_connect($mysql_servername , $mysql_username , $mysql_password);
mysql_select_db($mysql_database);
$name=$_POST['name'];
$passowrd=$_POST['password'];

if ($name && $passowrd){
$sql = "SELECT * FROM liuyanban WHERE name = '$name' and password='$passowrd'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows){
header("refresh:0;url=a.htm");//跳转页面,注意路径
exit;
}
echo "";
}else {
 echo "";
}

?>

The code is as follows Copy code

error_reporting(0);
$mysql_servername = "localhost"; //Host address
$mysql_username = "root"; //Database username
$mysql_password = ""; //Database password
$mysql_database ="peng"; //Database
mysql_connect($mysql_servername, $mysql_username, $mysql_password);
mysql_select_db($mysql_database);
$name=$_POST['name'];
$passowrd=$_POST['password'];

if ($name && $passowrd){
$sql = "SELECT * FROM liuyanban WHERE name = '$name' and password='$passowrd'";
$res = mysql_query($sql);
$rows=mysql_num_rows($res);
if($rows){
header("refresh:0;url=a.htm");//Jump to the page, pay attention to the path
exit;
}
echo "";
}else {
echo "";
}

?>

There is another one written by me who just learned PHP
 代码如下 复制代码

This is a rendering of the login page, other login aliases and passwords
The code is as follows Copy code

php code

The code is as follows Copy code
 代码如下 复制代码

session_start();//这个一定要申明喽,给个小提示:在session之前不能有任何输出哦,在php.5以下的版本会有问题.

$myname =get_value('myname',post);
$mypass =get_value('mypass',post);
if(!preg_match("/^w+$/",$myname) || strlen($myname)<3 || strlen($myname)>15 ){
  alert('输入的用户名信息有误!用户名必须由数字下划线英语字母组成,长度为3-15个字符!','');
 }
 if(!preg_match("/^w+$/",$mypass) || strlen($mypass)<6 || strlen($mypass)>15 ){
  alert('输和的用户密码!密码必须由数字下划线英语字母组成,长度为6-15个字符!','');
 }
 $sql ="select * from tbn where admin_name='$myname' and admin_pwd='".md5($mypass)."'";
 $result =mysql_query($sql);
 if(mysql_num_rows($result) ){
  $my =mysql_fetch_array($result);
  $_SESSION['uid']=$myname;
  //$_SESSION['auth']=return_auth($my['group_id']);  //这里是因为用到用户组取得用户组的权限
  header("location:main.php");
 }else{
  alert('提示:你输入的用户名与密码不一致!','');
 }

?>

session_start();//This must be declared. Here is a tip: there cannot be any output before the session. There will be problems in versions below php.5.


$myname =get_value('myname',post);

$mypass =get_value('mypass',post);
代码如下 复制代码

//数据库的地位
define(""DB_HOST"", ""127.0.0.1"");
//用户名
define(""DB_USER"", ""root"");
//口令
define(""DB_PASSWORD"", ""19900101"");
//数据库名
define(""DB_NAME"",""test"") ;
?>

if(!preg_match("/^w+$/",$myname) || strlen($myname)<3 || strlen($myname)>15 ){ alert('The entered username information is incorrect! The username must be composed of numbers, underscores, and English letters, and the length is 3-15 characters!',''); } if(!preg_match("/^w+$/",$mypass) || strlen($mypass)<6 || strlen($mypass)>15 ){ alert('Enter the user password! The password must be composed of numbers and underscores, English letters, and the length is 6-15 characters!',''); } $sql="select * from tbn where admin_name='$myname' and admin_pwd='".md5($mypass)."'"; $result =mysql_query($sql); if(mysql_num_rows($result) ){ $my =mysql_fetch_array($result); $_SESSION['uid']=$myname; //$_SESSION['auth']=return_auth($my['group_id']); //This is because the user group is used to obtain the permissions of the user group header("location:main.php"); }else{ alert('Tips: The username and password you entered are inconsistent!',''); } ?> In the above example, I only saved the information to the session. Let’s take a look at using session and cookie to save user login information at the same time 1. Database connection device page: connectvars.php
The code is as follows Copy code
//Database status<🎜> define(""DB_HOST"", ""127.0.0.1"");<🎜> //Username<🎜> define(""DB_USER"", ""root"");<🎜> //Password<🎜> define(""DB_PASSWORD"", ""19900101"");<🎜> //Database name<🎜> define(""DB_NAME"",""test"");<🎜> ?>

2. Login page: logIn.php

The code is as follows Copy code

//Insert relevant information to connect to the 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 to perform 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);
//Use username and password to query. If the found record is exactly one, set SESSION and COOKIE, 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""];
              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 found record does not match the error, 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);
}
?>


              Mismatch - Log In
          


                                                                                                                    & Lt;!-Through the $ _Sactive ["User_id" "], if the user fails to log in, the login form is displayed so that the user enters the username and the code-& gt;
                                                                                  If(!isset($_SESSION[""user_id""])){
                  echo ""

"".$error_msg.""

"";
          ?>
            
           
">
                                                                                                                                                                                                                                       

               
                                value="" />

               

               
               

           
           
       


                }
        ?>
   


3、登入页面:loged.php

 代码如下
 代码如下 复制代码

//应用会话内存储的变量值之前必须先开启会话
session_start();
//若是会话没有被设置,查看是否设置了cookie
if(!isset($_SESSION[""user_id""])){
    if(isset($_COOKIE[""user_id""])&&isset($_COOKIE[""username""])){
        //用cookie给session赋值
        $_SESSION[""user_id""]=$_COOKIE[""user_id""];
        $_SESSION[""username""]=$_COOKIE[""username""];
    }
}
//应用一个会话变量搜检登录状况
if(isset($_SESSION[""username""])){
    echo ""You are Logged as "".$_SESSION[""username""].""
"";
    echo "" Log Out("".$_SESSION[""username""]."")"";
}
/**在已登录页面中,可以哄骗用户的session如$_SESSION[""username""]、
 * $_SESSION[""user_id""]对数据库进行查询,可以做很多多少很多多少工作*/
?>

复制代码
"";     echo "" Log Out("".$_SESSION[""username""]."")""; } /**In the logged-in page, the user's session can be deceived, such as $_SESSION[""username""], * $_SESSION[""user_id""] queries the database and can do a lot of work*/ ?>

4. Log out the session and cookie page: logOut.php (redirect to lonIn.php after publishing)

session_start(); //Use a session variable to check the login status
The code is as follows
 代码如下 复制代码

/**同时刊出session和cookie的页面*/
//即使是刊出时,也必须起首开端会话才干接见会话变量
session_start();
//应用一个会话变量搜检登录状况
if(isset($_SESSION[""user_id""])){
//要清除会话变量,将$_SESSION超等全局变量设置为一个空数组
$_SESSION = array();
//若是存在一个会话cookie,经由过程将到期时候设置为之前1个小时从而将其删除
if(isset($_COOKIE[session_name()])){
setcookie(session_name(),"""",time()-3600);
}
//应用内置session_destroy()函数调用撤销会话
session_destroy();
}
//同时将各个cookie的到期时候设为畴昔的某个时候,使它们由体系删除,时候以秒为单位
setcookie(""user_id"","""",time()-3600);
setcookie(""username"","""",time()-3600);
//location首部使浏览看重定向到另一个页面
$home_url = ""logIn.php"";
header(""Location:"".$home_url);
?>

Copy code



/**Publish session and cookie pages at the same time*/

//Even when publishing, you must first start a session to access session variables
if(isset($_SESSION[""user_id""])){

//To clear session variables, set the $_SESSION super global variable to an empty array

$_SESSION = array();

//If a session cookie exists, delete it by setting the expiry time to 1 hour before ​​​​ setcookie(session_name(),"""",time()-3600); } //Apply the built-in session_destroy() function call to cancel the session Session_destroy(); } //At the same time, set the expiration time of each cookie to a time in the past so that they can be deleted by the system. The time is in seconds setcookie(""user_id"","""",time()-3600); setcookie(""username"","""", time()-3600); //The location header redirects the browser to another page $home_url = ""logIn.php""; header(""Location:"".$home_url);
?>
User registration and login involves the interaction between user information and the database, so special attention must be paid to the information submitted by the user not being illegal. In this example, the registration part has been restricted using regular expressions, and htmlspecialchars is simply used for the login part. () processing, it can be more stringent in actual application. This tutorial simply demonstrates the process of user registration and login. Its code is for learning reference only and cannot be directly used for project production. In this tutorial, session is used to manage the user after successful login. Cookie can also be used to manage, especially for time-limited requirements. In order to improve the user experience, the user registration part can be combined with AJAX to detect the information entered by the user without waiting for the user to click submit. http://www.bkjia.com/PHPjc/631288.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631288.htmlTechArticleThere are many kinds of basic user logins like my example. It is unsafe to run to the specified page. If the user knows your address, there is no need to log in. Example 2 uses...
Statement:
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