SoFunction
Updated on 2025-04-08

Complete tutorial on session in php page 1/2

1. Session Overview
What is session? I didn't understand at the beginning. The non-professional dictionary translates to meetings and meeting periods. Make an inappropriate metaphor
(Although it is inappropriate, the meaning is the same), session is the relationship between you and the website. Session accounts for a very important part of web technology. Since web pages are a stateless connection program, you cannot know the user's browsing status. So we must
Record the user's relevant information through session so that the user can confirm when providing requests to the web server as this identity again.
For example, we often require users to log in on some websites, but how do we know that the user has logged in? If there is no session, the login information cannot be retained. Then don’t let users provide username and password on every page of the web page.
Of course, session is not only used for user identity authentication functions, but also for other aspects, which we will mention in the future. The session is explained in Chinese as a session period. A session period begins when a user enters the URL of a site and ends when he leaves the site. session first appeared in the dynamic scripting language active server pages. Its powerful function is impossible to explain in one sentence.
When php is still in version 3.0, session is its eternal pain. Although php has the advantages of fast execution, flexible use, and powerful functions, due to the session problem, many website development has abandoned php, at least my boss thinks so. At that time, there were many free php function libraries that provided solutions to implement session on php3, but they all felt unauthentic. Just like the phone you bought for thousands of oceans but is equipped with a very rough straw bag. Although the functions are the same, it always makes people feel awkward. The emergence of php4 gives php a chance to turn around the session issue. Although its session implementation is not very ideal (mainly a matter of efficiency), it is implemented by itself and can be used in practice. Then why do we use session? If you talk for a long time, if I can't use it, wouldn't you be suspicious of selling paper? OK, let's take a look at what session is used for: people who have worked on websites have this experience. Variables in one page (all refer to server-side variables in this chapter, the same below) cannot be used on the next page. Although there are some ways to achieve it, such as form, urlstring, etc., some are inconvenient for users. Even if form is automatically submitted, the delay in it is enough to suffocate under the current network conditions, and both methods obviously increase the burden on programmers. If you are developing a large project, these additional burdens cannot be ignored. And it is easy to do with session. The variables registered in the session can be used as global variables. What, global variable? Very good. In this way, you know what it is used for: it is mainly used for user identity authentication, program status recording, and parameter transfer between pages.
After talking about its benefits for so long, you are already tempted. Don't be happy for now. It has its disadvantages: it is a variable that is saved using a file (of course it is not efficient, although it can be used in other ways, but it is very troublesome), and cannot save the object. In contrast, the session in asp can save object variables and use memory variables to save session variables. But why do we still use php? Haha, why, you can see this chapter from the beginning of this book, I believe you should understand it too. You don’t understand it yet, Faint, start from scratch again, I promise you to become a php expert^_^.
How is the session implemented? Haha, you must think it is very profound, I will tell you its secret. If you only save variables, many readers understand that this is very simple, but we said earlier that the http protocol is a stateless connection. How do you know whose variable belongs to and whose variable belongs to? It is implemented using cookies in the session implementation. The cookie exists in the client, that is, the user's machine, and it stores the user's session id, that is, the session number. When the user's browser requests the server, the session id is also sent to the server, so that the server can identify who you are and can identify the variables. In this way, it is not difficult for us to understand why the session sometimes fails. If you don't believe it, you can try: There is an "Internet Options" menu on the "Tools" menu of IE. After opening it, select "Security"->"Customization level", set "Allow each dialogue cookies" in the security settings to disable, and then see if the session can be used. Now you understand! However, php4 can automatically check the status of cookies on the Linux/unix platform. When cookies are not available, the session id will be automatically attached to the URL for delivery. This is its only advantage over Asp in terms of session.
2. Implementation of session in php3,4
There is no such thing as session in php3, but we need it, what should we do? Don't worry, there are many people who have done these for you, the most famous of which is phplib. You can download it abroad, and you can download it on most domestic php sites. The first thing we have to do is to get phplib and php3 together to make it work. In order to achieve this function, we need to install phplib first. Follow me, it is easy (the following method is passed on win2000+php3.0.16+apache1.3.12+phplib7.2c+mysql3.23.21 for win32) The most basic functions of phplib include user authentication, session management, permissions and database abstraction.
How to use phplib to implement session function?
1. First, you untie phplib, there is a directory called "php", and copy this directory to the installation directory of apache. Take my machine as an example: my apache is installed in the d:/apache directory. I copied the "php" directory above to d:a/pache, and copied the files and directories in the pages directory under phplib to d:/apache/htdocs, paying attention to not containing the directory itself. The phplib class library needs to be initialized according to the system. You can modify the file, which contains some basic parameters, which you can modify according to the actual situation of your machine. Change a program in the d:/apache/php/prepend.php3 file to the following:
if (!isset($_phplib) or !is_array($_phplib)) {
$_phplib["libdir"] = "d:/apache/php/"; //Change it to the path of the php directory under phplib
}
Then change the d:/apache/php/ file as follows:
class db_example extends db_sql {
var $host = "localhost";//The host name of your mysql database is located
var $database = "test";//Database name
var $user = "root";//Database username
var $password = "";//Database user password
}
The last step is to execute the create_database.mysql file in the unzipped phplib directory to generate the initial table. Let’s explain the working principle of phplib. Each page using phplib must first find the class library file that is necessary to run phplib. We can set the auto_prepend variable to support it. The phplib distribution package contains a prepend.php3 file. After auto_prepend is specified "d:/apache/php/prepend.php3" (with quotes), each page will automatically include the phplib class library. We can also add the directory where the phplib class library is located in to the include variable so that these files can be found. Of course, the most common way is to specify the absolute path of phplib. This is not a good idea, and the portability is too poor!
In the second step, in each page using phplib, you must first call the page_open function for initialization. This will tell phplib that you will use state saving now or in the future. A typical
The page_open example is as follows:
<?php
page_open(array("sess" => "example_session"));
?>
Array variables (sess) are used to initialize some state save objects. Note: the phplib built-in names (sess) must be used. These built-in names are defined in it. The page_open function must be called before the page content is output to the browser. The php3 script should end with page_close() at the end, which will write the relevant status data back to the database. If you forget, you should be able to think of it, haha, all your variables are lost, but don't blame me for not telling you...
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 page content here can be any html information or blank lines. If you find the error "oops - setcookie called after header has been sent", this indicates that what is output to the browser before page_open(), you should pay special attention to blank lines, because it is very difficult to find. A typical error is that blank lines are output between the <? and ? > tags. You should check whether blank lines are included in the prepend.php3 file, which is also a very easy place to make mistakes. In order to reduce the possibility of errors, we can write the initialization program like this:
<?
page_open(array("sess" => "example_session"));
?>
<html>
.....
</html>
Step 3: Use it in detail.
When a user visits the website, the user's session begins. If the user's browser supports cookies, a session id will be created and placed in the cookie. The only id is randomly generated by php3, and then md5 is encrypted with a random seed string. The cookie here should be called a session cookie, because this cookie will not be written to the user's hard disk. When a session period ends, the cookie is also completed. If the user's browser does not support cookies, the session id will be placed in the url chain. Because it is encrypted, it is useless to steal it. The session id stores user information, such as user authentication, authentication expiration date, user permissions, and other information you may need, for us to access. session is actually the process of a user's session. Session is not just used to track user registration. In fact, it can also be used in other usage scenarios. You can use it to store any information you want to store, which can come in handy in the pages the user will visit later, provided that those pages need to use phplib. The method is simple. After registering a variable, you can use it in the subsequent page until the session ends. method:
<?php $sess->register( "variable_name"); ?>
Note that the variable_name 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 accessing the variable will get the changed value. The types of variables are diverse, which can be a string, a number, and an array. Give an example to illustrate:
Page 1:
<?php
page_open(array("sess" => "example_session"));
$sess->register( "first"); //Note that you do not need to add $ before the variable name
if (iset($firstname)) {
$first = $firstname;
}
.....
page_close();
?>
Page 2:
<?php
page_open();//Start session
echo $first;// Check out the effect
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 and will have unpredictable consequences. When the variable is used and you no longer need to use it, you can call the following function to delete the variable:
<?php
page_open(array("sess" => "example_session"));
...
$sess->unregister( "variable_name");
...
page_close();
?>
In phplib 7.0, a storage structure is used, which allows you to store session data into a database, in shared memory, or in ldap. phplib uses database classes, which gives you more choices. You can choose oracle8, mysql, postgresql and other databases to save state information.
For other functions in phplib and other functions related to session, you can refer to the manual it comes with, or read the online documentation on its website. Its hometown is in /index.php3. Most of the session implementations of php4 are learned from phplib. It also relies on cookies to save session id and save variables using the file system (by default). Therefore, its session variable cannot save the object (in fact, it can save the object content, but it does not make sense because it is saved on disk, not a living object, at best, the object body.) However, this limitation is not too great. In most cases, we only need to save the variable. Of course, you can also save the session in the database. In the next section, we will talk about how to save the session in the database. In php4, there are more session configuration options in the file. Let’s take a look at the functions and significance of each item:
[session]
session.save_handler = files ; handler used to store/retrieve data (what to save session variables, file is used by default)
session.save_path = c:/temp ; argument passed to save_handler (the directory that saves session variables, /tmp under linux/unix, and set as your directory under win)
; in the case of files, this is the
; path where data files are stored
session.use_cookies = 1 ; whether to use cookies (whether to use cookies, of course, there is no choice under win)
= phpsessid
; name of the session (the name of the cookies used by the default session is not recommended to change)
; is used as cookie name
session.auto_start = 0 ; initialize session on request startup (whether session is enabled automatically? When it is 1, you don’t have to call the session_start() function in each page)
session.cookie_lifetime = 0 ; lifetime in seconds of cookie (Set the save time after the cookie is sent to the browser, in seconds. The default value is 0, indicating that the browser is closed.)
; or if 0, until browser is restarted
session.cookie_path = / ; the path the cookie is valid for(cookie)(cookies valid path)
session.cookie_domain = ; the domain the cookie is valid for(cookies valid domain name)
session.serialize_handler = php ; handler used to serialize data (Define the identification of serialized data. This function is only used internally by the wddx module or php. The default value is php)
; php is the standard serializer of php
session.gc_probability = 1 ; percent probability that the (sets the probability of starting processing for each temporary file (gc, garbage collection). The default value is 1. )
; 'garbage collection' process is started
; on every session initialization
session.gc_maxlifetime = 1440 ; after this number of seconds, stored (set the number of survival seconds before the temporary file that saves the session is cleared)
; data will be seen as 'garbage' and
; cleaned up by the gc process
session.referer_check = ; check http referer to invalidate (Decide whether the session code referenced to the client should be deleted. Sometimes, when security or other considerations, it is set to not delete. The default value is 0.)
; externally stored urls containing ids
session.etropy_length = 0 ; how many bytes to read from the file(Sets the number of bits that the session reads from high entropy resources. The default value is 0.)
session.entropy_file = ; specified here to create the session id (When setting the session code is created, external high entropy resources or files are used, such as /dev/random or /dev/urandom on a unix system.)
; session.entropy_length = 16
; session.entropy_file = /dev/urandom
session.cache_limiter = nocache ; set to { nocache,private,public } to (set session buffering limit)
; determine http caching aspects
session.cache_expire = 180 ; document expires after n minutes (the document validity period is in minutes)
Under the Windows platform, the previous version of php4.01pl2 will have an error after setting session.save_path. This is a bug in php, which has been fixed in php4.01pl2 and later. If you use the previous version, you can set session.save_path to "./", or set to "/temp", and create a directory called temp in the current root directory where you place the php script (my php script is placed under d:apachehtdocs, then I create a directory called temp in the root directory of the d: disk).
In php4, the main functions about session are as follows:
session_start: Initializing session, you need to call it at the beginning of each page of the session.
session_destroy: End session, adjust when the session needs to be ended.
session_name: Access the current session name.
session_module_name: Accesses the current session module.
session_save_path: Accesses the current session path.
session_id: Access the current session id number.
session_register: Register a new session variable.
session_unregister: Delete registered session variable.
session_is_registered: Check whether the session variable is registered.
session_decode: session data decoding.
session_encode: session Data encryption.
Usually we only need to call three functions.
That is, session_start(), session_register(), session_is_registered().
Call the session_start() function at the beginning of each page where the session needs to be used.
A typical page using session is as follows:
<?session_start()?>
<html>
....
<body>
<?
$var="hello";
session_register("var");//Register $var variable, note that there is no $ symbol
if(session_is_registered("var"))//Check whether the variable is registered
echo "haha, registered!";
else
echo "sorry, not registered yet!";
?>
</body>
</html>
Customization of session processing in php4
We need to expand 6 functions, of course, these functions do not require you to call them, and are transparent to us.
These functions are:
sess_open($sess_path, $session_name);
This function is called by the session handler for initialization. The two parameters that need to be passed to it are $sess_path, which corresponds to the session.save_path option in your file; $session_name, which corresponds to the options in it. How they work, please see the following examples.
sess_close();
This function is called when the page is executed at the end and the session handler needs to be closed. (Note, don't be confused with sess_destory, it is used to end the session)
sess_read($key);
This function is when the session handler reads the specified session key value ($key).
This function retrieves and returns session data identified as $key. (Note: you don't have to worry about how to serialize and deserialize the data. If you don't know what this means, don't worry about it)
Translator's note: Serialization is to save variables or objects in a file when the program ends or needs it, and then the next time the program runs or needs it.
The technique of typing into memory 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 happens at the end of your 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.
Now we have the function we provide.
Customized programs can save session data using mysql database or dbm file. Depends on your needs.
If you decide to use mysql for support, you need to do the following:
First we create a session database in mysql and create a session table. First run your mysql client and execute the following command:
mysql> create database sessions;
mysql> grant select, insert, update, dele 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 session_mysql.php file to match the database settings on your machine.
12Next pageRead the full text