Session refers to the time that elapses from entering the website to closing the browser when the user is browsing a website, that is, the time the user spends browsing the website. From the above definition, we can see that Session is actually a specific time concept.
Generally speaking, variables (referring to server-side variables, the same below) in a certain page on the website cannot be used in the next page. It is easier to handle with session. 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 is session implemented in the 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. Next we will describe how to use phplib to implement session.
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. 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 in the pages directory of the phplib directory (excluding the directory itself) to d: Under Apachehtdocs.
The phplib class library needs to be initialized according to the system, and the local.inc file may need to be modified, which contains some basic parameters, which can be modified according to the actual situation of your own machine.
Change the program in the d:Apachephpprepend.php file to the following:
if (!isset($_PHPLIB) or !is_array($_PHPLIB)) {
$_PHPLIB["libdir"] = "d:/Apache/php/"; //The path to the php directory under phplib
}
Modify the d:Apachephplocal.inc file:
class DB_Example extends DB_Sql {
var $Host = "localhost"; //The host name of the mysql database var $Database = "test"; //Database name var $User = "root"; //Database user name var $Password = "1234567"; // Database user password
}
Finally, the initial table is generated based on the create_database.mysql file in the stuff subdirectory under the phplib directory.
Since every page that uses phplib must first be able to find the class library files necessary to run phplib, we can set the auto_prepend variable in php.ini to support it. phplib contains a prepend.php file and specifies auto_prepend as "d: /Apache/php/prepend.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 to the include variable so that these files can be found. 2. Call the page_open() function.
In every page using phplib, you must first call the page_open function for initialization, for example:
<?php
page_open(array("sess" => "Test_Session"));
?>
Array variables (sess) are used to initialize some state saving objects. It should be noted here: phplib built-in names (sess) must be used. These built-in names are defined in local.inc.
Because phplib uses Cookies to save state 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(), which will write the relevant status data back to the database, otherwise the variables will be lost.
3. Specific use.
After registering a variable, you can use it in subsequent pages until the session ends. Method:
<?php $sess->register( "varname"); ?>
Note that 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 on a certain page, and the changed value will be obtained when the variable is accessed on subsequent pages. The types of variables are diverse and can be a string, a number, or an array. For example:
first page:
<?php
page_open(array("sess" => "Test _Session"));
$sess->register( "welcome"); //Register variable $welcome, note that there is no need to add $
$welcome="Hello,PHP world!";
…
page_close();
?>
Second page:
<?php
page_open();//Start session
echo $welcome;//Display $welcome defined in the first page
page_close();//Save status information
?>
After registering a variable, when the page finally calls the page_close() function, each session variable will be written back to the database. If you forget to call the page_close() function, the variables will not be written back to the database, which will have unpredictable consequences. When the variable has been used and is no longer needed, the following function can be called to delete the variable:
<?php
page_open(array("sess" => "Test _Session"));
…
$sess->unregister( "variable_name");
…
page_close();
?>
How to implement session in PHP4 version?
PHP4's session also relies on cookies to save session ids and uses the file system to save variables (by default). Therefore, its session variables cannot save objects. Of course, the session can also be saved in the database.
There are many functions related to session in php4 (see the article php.ini configuration for details). Normally we only need to call three functions: session_start(), session_register(), session_is_registered().
Call the 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 there is no $ symbol if(session_is_registered("welcome"))//Check whether $welcome variable is registered echo "welcome variable has been registered!";
else
echo "The welcome variable has not been registered yet!";
?>
</body></html>
To customize 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 php.ini file. The parameter $session_name corresponds to the session.name option in php.ini.
·sess_close();
This function is called when the page ends execution and the session handler needs to be closed.
·sess_read($key);
This function retrieves and returns the identifier when the session handler reads the specified session key value ($key). $key’s session data. (Note: Serialization is a technology that saves variables or objects in a file at the end of the program or when needed, and then transfers them into the memory when the program runs or is needed next time. It is different from the method of only saving data. )
·sess_write($key, $val);
This function is called when the session handler needs to save the data, which often happens at the end of the program. It is responsible for saving the data in a place where it can be retrieved next time using the sess_read($key) function.
·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. Session handlers call them occasionally.
The custom program can use a mysql database or DBM file to save session data, depending on the specific situation. If you use mysql for support, you need to perform 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* variables in 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");
……//Customized function
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");
……//Customized function
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");//Which interface to use
elseif ($handler == "mysql") include("session_mysql.php");
else…
session_start();
session_register("count");
…
?>
How to use Session in authentication?
Session can be used for user authentication:
verify whether the user is legitimate:
<?
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 logs out:
<?
session_destroy();
…
?>
How to implement multiple sessions running concurrently?
Question: When I was writing a purchase, sales and inventory system for my unit, I found that it was necessary to allow multiple users to enter a PHP application at the same time. The originally designed static unique session ID caused data confusion. In this way, dynamically generating a unique session ID becomes a top priority.
The solution is simple: I used the php file name + timestamp as the unique session ID, so that each session in my program is in its place and there is no longer confusion.
I will publish my source code below so that friends who have the same problem can find a solution.
//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 for the unique sessionname between pages. If you also use this name, you must make a small change in the above program. Mysessionname cannot be the internal variable name of the session because it already exists before the session starts. Mysessionname cannot be stored in cookie mode, because multiple sessions will definitely overwrite the original cookie file. You can save it using hidden form fields. Then there will be no problem.