Home Backend Development PHP Tutorial How to save user login information in session in php_PHP tutorial

How to save user login information in session in php_PHP tutorial

Jul 13, 2016 pm 05:15 PM
php session thing keep information exist accomplish yes user Log in

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles