Detailed explanation of session in PHP 2
Summary
Session refers to the time when a user browses a website from entering the website to closing the browser, which is the time it takes for the user to browse the website. From the above definition we can see that Session is actually a specific concept of time.
Generally speaking, variables (referring to server-side variables, the same below) cannot be used on the next page, and session is easy to do. The variables registered in the session can be used as global variables. In this way, we can use session for user identity authentication, program status recording, and parameter transfer between pages.
How to implement session in PHP3 version?
php3 itself does not implement the session function, we can only use other methods to implement it, the most famous of which is phplib. The most basic functions of phplib include user authentication, session management, permissions and database abstraction. Let’s talk about how to implement session using phplib.
1. First install phplib (the environment is win2000+php3.0.16+Apache1.3.12+phplib7.2c+mysql3.23.21 for win32)
First unzip phplib, there is a "php" directory inside, and copy this directory to the Apache installation directory. For example: Apache is installed in the d:\Apache directory, then copy the "php" directory to d:\Apache, and copy the files and directories of the pages directory of the phplib directory (excluding the directory itself) to d:\Apache\htdocs.
The phplib class library needs to be initialized according to the system, and may need to modify the file, which contains some basic parameters, which can be modified according to the actual situation of your machine.
Change a program in the d:\Apache\php\ file to the following:
Copy the codeThe code is as follows:
if (!isset($_PHPLIB) or !is_array($_PHPLIB)) {
$_PHPLIB["libdir"] = "d:/Apache/php/"; //Put the path of the php directory under phplib
}
Modify d:\Apache\php\file:
class DB_Example extends DB_Sql {
var $Host = "localhost"; //The host name where the mysql database is located
var $Database = "test"; //Database name
var $User = "root"; //Database username
var $Password = "1234567"; //Database user password
}
Finally, generate the initial table based on the create_database.mysql file in the stuff subdirectory under the phplib directory.
Since each page using phplib must first find the class library file necessary to run phplib, we can set the auto_prepend variable to support it. phplib contains a file and specify auto_prepend as "d:/Apache/php/" (with quotes), each page will automatically include the phplib class library. We can also add the directory where the phplib class library is located into the include variable so that these files can be found.
2. Call the page_open() function
In every page using phplib, the page_open function must be called first for initialization, for example:
Copy the codeThe code is as follows:
<?php
page_open(array("sess" => "Test_Session"));
?>
Array variables (sess) are used to initialize some state-save objects. Here you should note: phplib built-in names (sess) must be used, and these built-in names are defined in.
Because phplib uses cookies to save status information, the page_open() function must be called before the page content is output to the browser. The php script should end with page_close() at the end, which will write the relevant status data back to the database, otherwise the variable will be lost.
3. Specific use.
After registering a variable, you can use it in the subsequent page until the session ends. method:
<?php $sess->register( "varname"); ?>
Note that the varname here is not a variable value, but a variable name. You can specify the variable name first and then assign the value. You can change the value of a variable in a certain page, and the subsequent page will get the changed value when accessing the variable. Variable types are diverse, and can be a string, a number, and an array. Give an example to illustrate:
Page 1:
<?php
page_open(array("sess" => "Test _Session"));
$sess->register( "welcome"); //Register the variable $welcome, note that you do not need to add $
$welcome="Hello,PHP world!";
……
page_close();
?>
Page 2:
<?php
page_open();//Start session
echo $welcome;//Show $welcome defined in the first page
page_close();//Save status information
?>
After registering a variable, when the page_close() function is called at the end of the page, each session variable will be written back to the database. If you forget to call the page_close() function, the variable will not be written back to the database, which will have unpredictable consequences. When the variable is used and no longer needed, the following function can be called to delete the variable:
Copy the codeThe code is as follows:
<?php
page_open(array("sess" => "Test _Session"));
……
$sess->unregister( "variable_name");
……
page_close();
?>
How to implement session in PHP4 version?
The session of php4 also relies on cookies to save session id and use the file system to save variables (by default), so its session variable cannot save objects. Of course, you can also save the session in the database.
There are many functions about session in php4 (see the configuration article for details). Generally, we only need to call three functions: session_start(), session_register(), and session_is_registered().
Call session_start() function at the beginning of each page that requires session, for example:
<?session_start()?>
<html><body>
<?
$welcome="hello world !";
session_register("welcome");//Register $welcome variable, note that there is no $ symbol
if(session_is_registered("welcome"))//Check whether the $welcome variable is registered
echo "welcome variable has been registered!";
else
echo "welcome variable has not been registered yet!";
?>
</body></html>
Customization of session processing in php4
We need to expand 6 functions:
sess_open($sess_path, $session_name);
This function is called by the session handler for initialization.
The parameter $sess_path corresponds to the session.save_path option in the file
The option in the parameter $session_name corresponds to.
sess_close();
This function is called when the page is executed at the end and the session handler needs to be closed
sess_read($key);
This function retrieves and returns session data identified as $key when the session handler reads the specified session key value ($key). (Note: Serialization is a technique of saving variables or objects in a file when the program ends or needs it, and then redirecting them into memory the next time the program runs or needs it, which is different from the method of only saving data.)
sess_write($key, $val);
This function is called when the session handler needs to save data, which often occurs at the end of the program. It is responsible for storing the data in a place where it can be retrieved with the sess_read($key) function next time.
sess_destroy($key);
This function needs to destroy the session. It is responsible for deleting the session and clearing the environment.
sess_gc($maxlifetime);
This function is responsible for cleaning up fragments. In this case, it is responsible for deleting outdated session data. The session handler will call them occasionally.
Customized programs can use mysql database or DBM files to save session data, depending on the specific situation. If you use mysql for support, you need to follow the following steps:
First, create a sessions database in mysql and create a sessions table:
mysql> CREATE DATABASE sessions;
mysql> GRANT select, insert, update, delete ON sessions.* TO phpsession@localhost
-> IDENTIFIED BY 'phpsession';
mysql> CREATE TABLE sessions (
-> sesskey char(32) not null,
-> expiry int(11) unsigned not null,
-> value text not null,
-> PRIMARY KEY (sesskey)
-> );
Next, modify the $SESS_DB* variable of the session_mysql.php file to match the database settings on your machine:
<?
$SESS_DBHOST = "localhost"; /* database host name */
$SESS_DBNAME = "sessions"; /* Database name */
$SESS_DBUSER = "phpsession"; /* Database username */
$SESS_DBPASS = "phpsession"; /* Database Password */
$SESS_DBH = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
…//Customize functions
session_set_save_handler( "sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
?>
Customize the interface when using dbm files:
<?
$SESS_DBM = "";
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime");
…//Customize functions
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");
?>
session customized test code:
<?php
……
if ($handler == "dbm") include("session_dbm.php");//What interface should be used
elseif ($handler == "mysql") include("session_mysql.php");
else ……
session_start();
session_register("count");
……
?>
How to apply Session in authentication?
Session can be used for user authentication:
Verify that the user is legal:
<?
session_start();
...//Verification process
session_register("reguser");
?>
Check whether the user is logged in on another page
<?
session_start();
if(isset($reguser)&&$reguser!=""){//If you have logged in
echo "Dear user, welcome";
}else{//If you are not logged in
echo "Please register first!";
}
?>
User logout:
<?
session_destroy();
……
?>
How to implement concurrent operation of multiple sessions?
The problem is raised: When I was writing a purchase and sales system for my unit, I found that multiple users need to enter a php application at the same time. The original design of the static unique session ID causes data confusion. In this way, dynamically generating a unique session ID becomes an urgent task.
The solution is very simple: I used the php file name + timestamp as the unique session ID, so that every session in my program will be in place and no longer be confused.
I will publish my source code below to facilitate friends who also have the same problem to solve it.
//Start a PHP session to preserve variables.
if ( empty($mysessionname) ) {
$micro = microtime();
$micro = str_replace(" ","",$micro); // strip out the blanks
$micro = str_replace(".","",$micro); // strip out the periods
$mysessionname = "po_maint" . $micro;
}
session_name($mysessionname);
session_start();
Program Notes:
Use mysessionname to pass variables as the unique sessionname between pages. If you also use this name, you must make a small change to the above program. Mysessionname cannot be the internal variable name of the session because it exists before the session begins. Mysessionname cannot be stored in cookies, because multiple sessions will definitely overwrite the original cookie file. You can save it with the fields that implicit forms. This way there will be no problems.