Home  >  Article  >  Backend Development  >  How to save user login information in session in php_PHP tutorial

How to save user login information in session in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:15:171778browse

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. .

Simple session creation

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

session_start();
$username = "nostop";
session_register("username");
?>

session_start();

$username = "nostop";

session_register("username");

?>

In this example, we register a variable named username with session and its value is nostop.
 代码如下 复制代码

例子:
session_start();
echo "登记的用户名为:".$_SESSION["username"]; //输出 登记的用户名为:nostop
?>

Read session

 代码如下 复制代码

session_unregister()  注销单个 session 变量
unset($_SESSION['age']); 用于注销以$_SESSION['age']注册的session变量
session_unset()  删除所有已注册的变量
session_destroy() 注销所有的session变量,并注销整个 session 会话

PHP’s built-in $_SESSION variable can easily access the set session variables.

The code is as follows Copy code
Example:
 代码如下 复制代码
session_start();
session_unregister("username"); //注销 session 某个变量
session_unset(); //注销 session 会话
?>
session_start();
echo "Registered user name:".$_SESSION["username"]; //Output Registered user name: nostop

?>

Destroy session
 代码如下 复制代码


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

The code is as follows Copy code
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
The code is as follows Copy code
//Database location<🎜> define('DB_HOST', 'localhost');<🎜> //Username<🎜> define('DB_USER', 'root');<🎜> //Password<🎜> define('DB_PASSWORD', '19900101');<🎜> //Database name<🎜> define('DB_NAME','test') ;<🎜> ?>

Login page: logIn.php

The code is as follows Copy code

//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 '

'.$error_msg.'

';
          ?>
           
           

                                                                                                                  Log In

                                                                                                                    
                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                             value="" />

                                                                                                

               
               

           
           
       


                }
        ?>
   


3、登入页面:loged.php

//使用会话内存储的变量值之前必须先开启会话
 代码如下
 代码如下 复制代码


//使用会话内存储的变量值之前必须先开启会话
session_start();
//使用一个会话变量检查登录状态
if(isset($_SESSION['username'])){
echo 'You are Logged as '.$_SESSION['username'].'
';
    //点击“Log Out”,则转到logOut页面进行注销
    echo ' Log Out('.$_SESSION['username'].')';
}
/**在已登录页面中,可以利用用户的session如$_SESSION['username']、
 * $_SESSION['user_id']对数据库进行查询,可以做好多好多事情*/
?>

复制代码

 代码如下 复制代码

//即使是注销时,也必须首先开始会话才能访问会话变量
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();
}
//location首部使浏览器重定向到另一个页面
$home_url = 'logIn.php';
header('Location:'.$home_url);
?>

session_start();

//使用一个会话变量检查登录状态

if(isset($_SESSION['username'])){

    echo 'You are Logged as '.$_SESSION['username'].'
';     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)
 代码如下 复制代码
//即使是注销时,也必须首先开始会话才能访问会话变量<🎜> 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();<🎜> }<🎜> //location首部使浏览器重定向到另一个页面<🎜> $home_url = 'logIn.php';<🎜> header('Location:'.$home_url);<🎜> ?> http://www.bkjia.com/PHPjc/628874.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/628874.htmlTechArticlesession在php中是一个非常重要的东西,像我们用户登录一般都使用到session这个东西,相对于cookie来说session 要安全很多,同时我们财物车经常...
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