Home >Backend Development >PHP Tutorial >Complete tutorial on session in php page 1/2_PHP tutorial
1. Overview of session
What is session? I didn’t understand it at first. Non-professional dictionaries translate it into meeting and meeting period. Let’s make an inappropriate metaphor
(although inappropriate, the meaning is the same), session is the relationship between you and the website. Session plays a very important role in web technology. Since the web page is a stateless connection program, you cannot know the user's browsing status. Therefore, we must
record the relevant information of the user through the session so that the user can confirm when providing a request to the web server again in this capacity. For example,
we often require users to log in on some websites, but how do we Knowing that the user has logged in, if there is no session, the login information cannot be retained, then why not ask the user to provide a user name and password on every web page.
Of course, session is not only used for user identity authentication, but may also be used for other aspects, which we will mention later. Session is explained in Chinese as session period. A session begins when the 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 function is so powerful that it cannot be explained clearly in one sentence.
When PHP was still in version 3.0, session was its eternal pain. Although PHP has the advantages of fast execution speed, flexible use, and powerful functions, many website developers have abandoned PHP because of session problems, at least my boss thinks so. At that time, there were many PHP free function libraries that provided solutions for implementing sessions on PHP3, but they all felt unauthentic. It's like the mobile phone you bought for thousands of dollars comes with a rough straw bag. Although the functions are the same, it always feels awkward. The emergence of php4 has given PHP a chance to make a comeback on the session issue. Although its session implementation is not ideal (mainly due to efficiency issues), it is implemented by itself after all, and it can be actually used. So what do we use session for? You've been talking for a long time. If I don't use it, wouldn't you be suspected of selling paper? Ok, let’s see what the session is used for: Anyone who has worked on a website has this experience. The variables on one page (in this chapter all refer to server-side variables, the same below) cannot be used on the next page. Although there are some ways to achieve this, such as using forms, urlstrings, etc., some are inconvenient for users. Even if the form is automatically submitted, the delay is enough to suffocate under today's network conditions, and this Both methods significantly increase the burden on programmers. If you are developing a large project, these additional burdens cannot be ignored. With session, it is easier to handle. Variables registered in session can be used as global variables. What, global variables? Great. In this way, you know what it is used for: the most important ones are used for user identity authentication, program status recording, and parameter transfer between pages.
Having talked about its benefits for so long, you are already tempted, but don’t be happy yet. It also has shortcomings: it is a variable saved in a file (of course it is not efficient. Although it can be used in other ways, it is very Troublesome), the object cannot be saved. In contrast, the session in asp can save object variables and use memory variables to save session variables. But why do we still choose PHP? Haha, why, you can read this chapter from the beginning of this book, I guess you should understand it. If you still don’t understand, faint, just start from the beginning again, I guarantee that you will become php expert^_^.
How is session implemented? Haha, you must think it is very profound, let me tell you its secret. If you only save variables, many readers will understand that this is very simple, but as we said before, the http protocol is a stateless connection. How do you know who the variable belongs to and who the variable belongs to? ?Achieved using cookies in session implementation. The cookie exists on the client, that is, the user's machine. It stores the user's session id, which 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. Who can also 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 the "Internet Options" menu on the "Tools" menu of IE. After opening it, select "Security"->"Custom Level" and change the "Allow use of each conversation" in the security settings. "Cookies" is set to disabled, and then see if the session can be used. Now you understand! However, php4 can automatically check the cookie status on the Linux/Unix platform. When the cookies are not available, the session ID will be automatically attached to the URL and passed. This is its only advantage over asp in terms of sessions.
2. Implementation of session in php3 and 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 this for you, the most famous of which is phplib. You can download it abroad, and you can download it from most domestic PHP sites. The first thing we need to do is get phplib and php3 together to make it work. In order to achieve this function, we need to install phplib first.Follow me, it's very 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 the session function?
1. First, unzip phplib. There is a directory called "php" in it. Copy this directory to the installation directory of apache. Take the author's 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 Under d:/apache/htdocs, be careful not to include the directory itself. The phplib class library needs to be initialized according to the system. You can modify the local.inc file, which contains some basic parameters. You can modify it according to the actual situation of your machine. Change a program in the d:/apache/php/prepend.php3 file to look like this:
if (!isset($_phplib) or !is_array($_phplib)) {
$_phplib["libdir" ] = "d:/apache/php/"; //Change here to the path of the php directory under phplib
}
Then change the d:/apache/php/local.inc file as follows:
class db_example extends db_sql {
var $host = "localhost";//The host name of your mysql database
var $database = "test";//Database name
var $user = "root ";//Database user name
var $password = "";//Database user password
}
The last step is to execute the create_database.mysql file in the stuff directory in the unpacked phplib directory to generate the initial surface. Let’s explain how phplib works. Every page that uses phplib must first find the class library files necessary to run phplib. We can set the auto_prepend variable in php3.ini to support it. The phplib distribution package contains a prepend.php3 file. After specifying "d:/apache/php/prepend.php3" (with quotes) for auto_prepend, 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 can be found. File, of course, the easiest way is to specify the absolute path of phplib. This is not a good idea, the portability is too poor!
Second step, in every page using phplib, you must first call the page_open function for initialization. This tells phplib that you will need to save the state now or in the future. A typical
page_open example is as follows:
page_open(array("sess" => "example_session"));
?>
Array variable (sess) Used to initialize some state saving objects. Note: phplib built-in names (sess) must be used. These built-in names are defined by you in local.ini. The page_open function must be called before the page content is output to the browser. The php3 script should end with page_close(), which will write the relevant status data back to the database. If you forget, you should be able to think of the result, haha, all your variables are lost, 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" indicates what was output to the browser before page_open(). You should pay special attention to blank lines, because they are very difficult to find. Typical errors are between and ? > Blank lines are output between tags. You should check whether the local.inc and prepend.php3 files contain blank lines. This is also a very error-prone place. In order to reduce the possibility of errors, we can write the initialization program like this:
page_open(array("sess" => "example_session"));
?>
.....
The third step is specific use.
When a user visits the website, the user's session starts immediately. If the user's browser supports cookies, a session ID will be created and placed in the cookie. This unique ID is randomly generated by php3. Then it is md5 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 drive. When a session ends, the cookie will also be completed. . If the user's browser does not support cookies, then the session ID will be put into the URL chain. Because it is encrypted, it is useless to steal it. The session ID stores user-related information, such as the user has been authenticated, authentication expiration time, user permissions, and other information you may need for our convenience. Session is actually the process of a user session. Session is not just used to track user registration. In fact, it can also have other uses. You can use it to store any information you want to store. This information can be sent to the pages that the user subsequently visits. Useful, of course, the premise is that those pages use phplib. The method is very simple. After registering a variable, you can use it in subsequent pages until the session ends. Method:
register( "variable_name"); ?>
Note that 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 page, and subsequent pages will get the changed value when accessing the variable. The types of variables are diverse and can be a string, a number, or an array. To illustrate:
First page:
page_open(array("sess" => "example_session"));
$sess->register( "first" ); //Note that there is no need to add $ before the variable name
if (iset($firstname)) {
$first = $firstname;
}
.....
page_close() ;
?>
Second page:
page_open();//Start session
echo $first;//See the effect
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, and unpredictable consequences will occur. When the variable is used and you no longer need it, you can call the following function to delete the variable:
page_open(array("sess" => "example_session"));
...
$sess->unregister( "variable_name");
...
page_close();
?>
In phplib 7.0, a storage is used Structure that allows you to store session data in a database, shared memory, or ldap. phplib uses database classes, which gives you more choices. You can choose oracle8, mysql, postgresql and other databases to save status information.
For other functions in phplib and the use of other functions related to session, you can refer to its manual, or go to its website to read online documentation. Its hometown is http://phplib.netuse.de/index.php3. Most of php4's session implementation is learned from phplib. It also relies on cookies to save session ids and uses the file system to save variables (by default). Therefore, its session variable cannot save the object (in fact, it can save the object content, but it is meaningless, because it is saved on the disk, not a living object, at best, it is an object corpse.) However, this limitation is not too big. , we only need to save variables in most cases. 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. Since php4 has more session support than php3, there are also more session configuration options in the php.ini file. Let’s take a look at the functions and meanings of each item:
[session]
session.save_handler = files; handler used to store/retrieve data (what to use to save session variables, files are used by default)
session.save_path = c:/temp; argument passed to save_handler (the directory where session variables are saved, /tmp under linux/unix, set to 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)
session.name = phpsessid
; name of the session (the cookie name used by the default session, it is recommended not to change)
; is used as cookie name
session.auto_start = 0; initialize session on request startup (whether to automatically enable the session, when it is 1, There is no need to call the session_start() function in each page)
session.cookie_lifetime = 0; lifetime in seconds of cookie (set the storage time after the cookie is sent to the browser, in seconds. The default value is 0 , means until 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 (defines the identifier 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; percentual probability that the (Set the processing probability each time a temporary file starts processing (gc, garbage collection). Default The value is 1. )
; 'garbage collection' process is started
; on every session initialization
session.gc_maxlifetime = 1440; after this number of seconds, stored(the temporary file set to save the session is cleared The number of seconds alive before)
; data will be seen as 'garbage' and
; cleaned up by the gc process
session.referer_check = ; check http referer to invalidate (determine to refer to the client's session code Whether to delete. Sometimes the default value is 0 for security or other reasons)
; externally stored urls containing ids
session.entropy_length = 0; how many bytes to read from the. file (set the number of bits that session reads from high-entropy resources. The default value is 0.)
session.entropy_file = ; specified here to create the session id (set session code to use external high-entropy when creating it) Create a value resource or file, 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 buffer limit)
; determine http caching aspects
session.cache_expire = 180 ; document expires after n minutes (document validity period, unit is minutes)
Under the windows platform, versions before php4.01pl2 will have an error after setting session.save_path In this case, this is a bug in php, which has been corrected in php4.01pl2 and later. If you use a previous version, you can set session.save_path to "./" or "/temp", and create a directory named temp in the root directory of the current disk 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 d: drive).
The session-related functions in php4 mainly include the following:
session_start: Initialize the session and need to be called at the beginning of each page using the session.
session_destroy: End session, called when the session needs to be ended.
session_name: access the current session name.
session_module_name: access the current session module.
session_save_path: access the current session path.
session_id: access the current session id number.
session_register: Register new session variables.
session_unregister: Delete registered session variables.
session_is_registered: Check whether the session variable is registered.
session_decode: session data decoding.
session_encode: session data encryption.
Normally 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 that needs to use session.
A typical page that uses session is as follows:
< ;html>
....
$var="hello";
session_register("var");//Register $var variable, Note that there is no $ sign
if(session_is_registered("var"))//Check whether the variable is registered
echo "haha, registered!";
else
echo "sorry, not registered yet!" ;
?>