php Session method instance

How to judge the user's operation authority through Session

In most of the web development process, according to the actual needs, it is necessary to divide the rights of administrators and ordinary users to operate the web site. The following is a comprehensive explanation through a specific code example.

(1) Design a landing page, add a form form, and use POST to pass parameters. The data processing page pointed to by action is default.php , add a user name text box and name it user, add a password field text box and name it pwd, and submit the jump through the submit button. The main code is as follows.

 

<html>
<head>
<script type="text/javascript">

 function check(form){

     if(form.user.value == ""){

         alert("enter one user name");

    }

     if(form.pwd.value == ""){

         alert("Please input a password");

    }

     form.submit();

}

  </script>
</head>
<body>
<form name="form1" method="post" action="default.php">

  <table width="520" height="390" border="0" cellpadding="0" cellspacing="0">

    <tr>

      <td valign="top">

        <table width="520" border="0" cellspacing="0" cellpadding="0">

          <tr>

            <td height="24" align="right">user name:</td>

            <td height="24" align="left">

              <input name="user" type="text" id="user" size="20">

            </td>

          </tr>

          <tr>

            <td height="24" align="right">password:</td>

            <td height="24" align="left">

              <input name="pwd" type="password" id="pwd" size="20">

            </td>

          </tr>

          <tr align="center">

            <td height="24" colspan="2">

              <input name="submit" type="submit" value="Submit" onclick="return check(form);">

              <input type="reset" name="reset" value="Reset">

            </td>

          </tr>

          <tr>

            <td height="76">

              <span>Superuser: admin &nbsp;Password: 111 </span>

              <br>

              <span>Ordinary users: cyy &nbsp;Password: 000 </span>

            </td>

          </tr>

        </table>

      </td>

    </tr>

  </table>

</form>
</body>
</html>

(2) Under the submit button click event, call the custom function check() to verify that the form element is empty. javascript code is used for validation.

<script type="text/javascript">

 function check(form){

     if(form.user.value == ""){

         alert("enter one user name");

    }

     if(form.pwd.value == ""){

         alert("Please input a password");

    }

     form.submit();

}

 </script>

(3) Submit form elements to data processing page default.php . Use session first_ The start() function initializes the session variable. When the POST method is used to receive the value of the form element, the user name and password obtained are assigned to the session variable respectively. The code is as follows:

<?php

 session_start();

 $_SESSION['user']=$_POST['user'];

 $_SESSION['pwd']=$_POST['pwd'];

?>

(4) In order to prevent other users from logging in the system illegally, if condition statement is used to judge the value of session variable. javascript knowledge is still used here, and its code is as follows:

 if($_SESSION['user']==""){

   echo '<script type="text/javascript">alert("Please use the right way to log in"); history.back();</script>';

 }

(5) On the data processing page default.php Add the following navigation bar code to judge the level of the current user, see whether the logged in user is an administrator or an ordinary user, and then output the different display:

<?php

 session_start();

 $_SESSION['user']=$_POST['user'];

 $_SESSION['pwd']=$_POST['pwd'];

 if($_SESSION['user']==""){

   echo '<script type="text/javascript">alert("Please use the right way to log in"); history.back();</script>';

 }

?>
<table align="center" cellpadding="0" cellspacing="0">

 <tr align="center" valign="middle">

   <td style="width: 140px; color: red;">Current user:

     <!-- Output current login user level-->

     <?php

       if($_SESSION['user']=="admin" && $_SESSION['pwd']=="111"){

         echo "administrators";

       }else{

         echo "Ordinary users";

       }

     ?>

   </td>

   <td width="70"><a href="default.php">home page</a><td>

   <td width="70">|<a href="default.php">article</a><td>

   <td width="70">|<a href="default.php">album</a><td>

   <td width="100">|<a href="default.php">Change Password</a><td>

   <?php

     if($_SESSION['user']=="admin" && $_SESSION['pwd']=="111") {   //If the current user is an administrator

      //Output user management if the current user is an administrator

      echo   '<td width="100">|<a href="default.php">user management </a><td>';

     }

   ?>

   <td width="100">|<a href="safe.php">Log off user</a><td>

 </tr>

</table>

(6) On top default.php Add a hyperlink page for logout user to the page safe.php , and safe.php Write the following code to delete the user Session and return to the login page:

<?php
session_start();
unset($_SESSION['user']);
unset($_SESSION['pwd']);
session_destroy();
header('location:index.php');

(7) Run this instance, enter the user name and password on the website user login page, and log in to the website as super user or ordinary user respectively.

 

 

 

 

Information processing instructions for php custom Session

When using Session technology to track users in the system, the default processing method of Session is to record the Session information of each user by files in the Web server php.ini In session.save_path the path to create the Session data file. Although this default processing method is convenient, it is also flawed. The main reason is that the Session mechanism itself can't be cross machine. For systems with large access, multiple servers are usually used for concurrent processing. If each server processes sessions separately, the purpose of tracking users can't be achieved. At this time, you need to change the processing mode of Session. You can use sharing technology to save Session information to other servers, or use database to save Session information.

No matter using database or sharing technology to share Session information, the principle is basically the same, all of which are based on Session in PHP_ set_ save_ Handler () function to change the default processing mode, and specify the callback function to customize the processing. The function is as follows:

session_set_save_handler(open, close, read, write, destroy, gc)

Check the documents for more information. I haven't used it yet

 

Description of session temporary file and cache in php

1. session temporary file

In the server, if the sessions of all users are saved to the temporary directory, the security and efficiency of the server will be reduced, and the site of opening the server storage will be very slow. The default session server file of PHP on Windows is stored in C:\WINDOWS\Temp. If the concurrent access is large or the session is established too much, there will be a large number of similar sessions in the directory_ For the session files of xxxxx, too many files in the same directory will lead to performance degradation, and may lead to file system errors after being attacked. For this situation, PHP body provides a better solution. In PHP, use the function session_save_path() can solve this problem.

Using php function session_save_path() stores session temporary files, which can alleviate the problems of server efficiency reduction and slow site opening caused by the storage of temporary files. The example code is as follows:

<?php
$path = './tmp';
session_save_path($path);
session_start();
$_SESSION['username'] = true;

Note: session_ save_ The path() function should be in session_ The start () function is called before.

2. session cache

The function of Session cache

(1) Reduce access to the database. Applications can read persistent objects from the cache much faster than they can retrieve data from the database.

(2) When there is a circular relationship between persistent objects in the cache, the Session will ensure that there is no dead cycle to access the object graph and the JVM stack overflow caused by the dead cycle.

(3) Ensure that the relevant records in the database are synchronized with the records in the cache. When the Session clears the cache, it will automatically check the dirty data. If the objects in the Session cache are inconsistent with the corresponding records in the database, the database will be updated according to the latest object properties.

Session cache uses session_ cache_ The syntax format of the limiter() function is as follows:

session_cache_limiter(cache_limiter)

Parameter cache_ The limiter is public or private. At the same time, session cache does not refer to the server-side but the client-side cache, which is not displayed in the server.

The setting of cache time is session_ cache_ The expire() function has the following syntax format:

session_cache_expire(new_cache_expire);

Parameter cache_expire is the session cache time, in minutes.

Note: the two session cache functions must be in session_ Call before start () function, otherwise it will be wrong.

The following is an example to understand the process of session caching page. The implementation code is as follows:

<?php
session_cache_limiter('private');
$cache_limit = session_cache_limiter(); // Enable client cache
session_cache_expire(30);
$cache_expire = session_cache_expire(); // Set client cache time
session_start();

 

Detailed explanation of session database storage instance in php

Although changing the Session storage folder can prevent the Session from filling up the temporary folder and causing site paralysis, it can be calculated that if a large website logs in 1000 people a day and 30000 people a month, there are 30000 Session files in the site, but you need to query one Session in these 30000 folders_ ID should not be a very easy thing. At this time, it needs to be applied to Session database storage, that is, Session in PHP_ set_ save_ Handle() function.

 

design process

First, create a table to store SESSION in Mysql database:

Table name tb_session

Table structure is

 

 

Description: session_key: is used to store the session ID

session_data: used to store the serialized data$_ Value in SESSION [];

session_time: used to save a time stamp. This time stamp refers to the valid period of time()+session when the current session is created. Note the session here_ The type of time is int, so you can compare the size when you operate the database!

 

modify php.ini Session in file_ set_ save_ Change the value of handler to user, as shown in the figure:

 

 

 

 

index.php User login interface

<?php
include("session_set_save_handler.php");//Introduce custom session storage mechanism

if(isset($_GET["login"])){//judge login Whether there is a value. If there is a value, log out,
    session_start();//As long as it needs to be used $_session Where the variable is, you need to turn on the callback function open
    session_destroy();//Here are the small details mentioned above. When there are session_destroy When it's before read Executed by callback function
}else{
    session_start();
    if(isset($_SESSION["user"])){//Determine whether this value has a definition. If there is a definition, it indicates the saved value session If it has not expired, go directly to the main content
        echo "<script>alert('You just came here a while ago');window.location.href='main.php';</script>";
    }
}
?>

<html>
<meta charset="utf-8">
<body>
<form action="index_ok.php" method="post">
//Account:<input type="text" name="user"><br>
//password:<input type="text" name="pwd">
<input type="submit" name="sub">
</form>
</body>
</html>

 

 

index_ok.php Form submission processing document

<?php
include("session_set_save_handler.php");
session_start();
if($_POST["sub"]){//$_post["sub"]If it has a value, it submits the query
    echo $_POST["sub"];
    if($_POST["user"]!="" && $_POST["pwd"]!=""){
        $_SESSION["user"]=$_POST["user"];
        $_SESSION["pwd"]=$_POST["pwd"];//The custom session management mechanism here will call the callback function write,Will be processed by the serialization processor (by $_session[]Variable formation) string writing to database
        echo "<script>alert('Login successful!');window.location.href='main.php';</script>";
    }
}

?>

 

 

main.php Main content page

<?php
include("session_set_save_handler.php");
session_start();

if(isset($_SESSION["user"])){
    echo "welcome".$_SESSION["user"];
    echo "<a href='index.php?login=0'>cancellation</a>";
}else{
    echo "You are not logged in yet. Please log in first!";
    echo "<a href='index.php'>Sign in</a>";
}

?>

 

 

session_set_save_handler.php Custom session storage mechanism function file

<?php

//Open session
function open(){
    //connect mysql data base
    global $con;
    $con = mysqli_connect('localhost','root','123456','test') or die('Database connection failed');
    mysqli_query($con,'set names utf8');
    return(true);
}

//close database
function close(){
    global $con;
    mysqli_close($con);
    return(true);
}

//read session_data
function read($key){
    global $con;
    //Set current time
    $time = time();
    $sql = "select session_data from tb_session where session_key = '$key' and session_time > $time ";
    $res = mysqli_query($con,$sql) or die('Query failed');
    if(!$res){
        printf("Error:%s\n",mysqli_error($con));
        exit;
    }

    $row = mysqli_fetch_array($res);
    if($row!=false){
        return($row['session_data']);
    }else{
        return "";//Be sure to return a null value instead of false
    }

}

//storage session
function write($key,$data){
    global $con;
    //Set failure time
    $time = 60*60;//1 hour
    //Get unix timestamp
    $lapse_time = time()+$time;
    $sql = "select session_data from tb_session where session_key = '$key' ";
    $res = mysqli_query($con,$sql);
    if(mysqli_num_rows($res) == 0){
        //No, create
        $sql = "insert into tb_session(session_key,session_time,session_data) values ('$key',$lapse_time,'$data')";
        //Single quotation mark for string, not for number
        $res = mysqli_query($con,$sql);
        if(!$res){
            printf("Error:%s\n",mysqli_error($con));
            exit;
        }
    }else{
        //Existing, update
        $sql = "update tb_session set session_key = '$key' ,session_data = '$data' ,session_time = $lapse_time where session_key = '$key' ";
        $res = mysqli_query($con,$sql);
    }
    return($res);
}

//eliminate session data
function destroy($key){
    global $con;
    //delete session
    $sql = "delete from tb_session where session_key = '$key' ";
    $res = mysqli_query($con,$sql);
    return($res);
}

//garbage collection
function overdue($expire_time){//This parameter is automatically passed in, that is session.gc_maxlifetime Maximum effective time, e.g. 1440 s;
    global $con;
    $lapse_time = time();
    $sql = "delete from tb_session where session_time < $lapse_time ";//Purge expired session
    $res = mysqli_query($con,$sql);
    return($res);
}

session_set_save_handler('open','close', 'read', 'write','destroy', 'overdue');

 

The database is as follows:

 

 

Detailed explanation of session time setting in php

1. The client does not prohibit cookies

(1) Using session_set_cookie_params() sets the Session expiration time, which is set by Session in combination with Cookie. If you want the Session to expire after one minute, the code example is as follows:

<?php

$time = 1*60;
session_set_cookie_params($time);
session_start();
$_SESSION['username'] = 'cyy';

Note: session_set_cookie_params() must be in session_start() before calling.

Note: this function is not recommended. It may cause problems in some browsers. Therefore, the failure time is usually set manually.

(2) Use the setcookie() function to set the expiration time for the Session. To make the Session expire after one minute, the code example is as follows:

<?php

session_start();
$time = 1*60;
setcookie(session_name(),session_id(),time()+$time.'/');
$_SESSION['username'] = 'cyy';

Note: in the above code setcookie() function, session_name is the name of the Session, session_id is the identity of the client user, because session_id is the only randomly generated name, so Session is relatively safe. The expiration time is the same as the Cookie's expiration time. The last parameter is optional, which is the path to place the cookie.

 

2. Cookie s are forbidden by the client

(1) It is the practice of many forums to remind users to open cookies before logging in.

(2) Settings php.ini In the file session.use_trans_sid =1, or turn on the - enable trans Sid option at compile time to let PHP automatically pass sessions across pages_ id.

(3) Hide the form passing session through GET method_ id.

(4) Use file or database to store session_id, which is called manually in inter page delivery.

The second method above is not described in detail, because users cannot modify the php.ini Documents. In the third method, we can't use cookies to set the expiration time, but the login situation hasn't changed. The fourth is the most important one. When developing an enterprise website, you can use session files to slow down the server. Here we will introduce the third method, which uses GET method for transmission. The example code is as follows, receiving the code of the page header:

<?php

$session_name = session_name();
$session_id = $_GET[$session_name];
session_id($session_id);
session_start();
$_SESSION['username'] = 'cyy';

Note: Session: a session will be generated after the page is requested_ ID. if cookies are forbidden at this time, session cannot be delivered_ ID, the next page in the request will regenerate a session_id, which causes the session to fail to pass between pages.

Tags: PHP Session Database SQL

Posted on Tue, 26 May 2020 02:46:38 -0700 by phpmady