Php session complete tutorial page 1/2

Source: Internet
Author: User
Tags php session php3 file random seed

I. session Overview
What is a session? I didn't understand it at the beginning. non-professional dictionaries are translated into meetings and meeting periods. Make an inappropriate metaphor.
(Although inappropriate, it means the same thing). session is the relationship between you and your website. Session plays an important role in web technology. Because a Web page is a stateless Connection Program, you cannot know the browsing status of the user. Therefore, we must
The session is used to record user information for confirmation when the user requests the web server in this identity again. For example:
For example, users are often asked to log on to some websites, but how do we know that the user has logged on? If there is no session, the login information cannot be retained, do not provide the user name and password on each page.
Of course, sessions are not only used for user identity authentication, but may also be used in other aspects, as we will mention later. The session is interpreted as the session period in Chinese. A session starts when a user enters a website and ends when he leaves the website. Session was first introduced in the dynamic scripting language active server pages. It is powerful and cannot be clearly stated in one sentence.
When php is still in version 3.0, session is always a pain point. Although php has the advantages of fast execution speed, flexible use, and powerful functions, but due to session problems, many sites have abandoned php development, at least my boss thinks so. At that time, many php free function libraries provided the solution to implement session on php3, but they all made people feel unauthentic. Just as if you spent thousands of oceans buying mobile phones but configured a rough grass bag, although the functions are the same, it is always awkward. The emergence of php4 gave php a chance to turn over the session issue. Although its session implementation is not ideal (mainly because of efficiency issues), it is implemented by itself and can be used in practice. What are we doing with session? If you have been talking about it for a long time and I cannot use it, wouldn't you sell paper. OK. Let's take a look at the usage of the session: all people who have made websites have such experiences. The variables on the page (in this chapter, they refer to server variables, the same below) it cannot be used on the next page. Although some methods can be implemented, such as form and urlstring, it is inconvenient for some users, even if the form is automatically submitted, however, the latency is sufficient to suffocate people in today's network conditions, and both methods obviously increase the burden on programmers. If you are developing a large project, the extra burden cannot be ignored. With session, the variables registered in the session can be used as global variables. What are global variables? Great. In this way, you know what is used: Mainly used for user identity authentication, program status record, and parameter transfer between pages.
After talking about the benefits of it for so long, you have already been tempted. Don't be happy first. It also has its disadvantages: it is a variable stored in a file (of course, the efficiency is not high, although it can be used in other ways, but it is very troublesome), the object cannot be saved. In contrast, sessions in asp can save object variables and use memory variables to save session variables. But why are we still using php? Well, why? You should have understood this chapter from the beginning of this book. You still don't understand it, faint, let's start from the beginning. I promise you will become a php expert ^_^.
How is the session implemented? Well, you must think it is very advanced. I will tell you its secret. If we only save variables, many readers understand that this is very simple, but as we have said before, http is a stateless connection. How do you know who the variable is, who is this variable? Cookie is used in session implementation. The cookie exists on the client, that is, the user's machine, which 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, in this way, the server can identify who you are, and the variable can be identified. In this way, we can easily understand why the session sometimes becomes invalid. If you don't believe it, you can try: there is an "internet Options" menu on the "Tools" menu of ie, and then choose "security"-> "Custom Level ", set "allow each session cookie" in the security settings to disabled and check whether the session can be used. Now, I understand! However, php4 can automatically check the cookie status on linux/unix platforms. When cookies are unavailable, the session id is automatically included in the url for transmission. This is the only advantage of session over asp.
Ii. session implementation in php3 and 4
There is no such thing as session in php3, but we need it again. What should we do? Don't worry. Many people have done this for you. The most famous one is phplib. You can download it from a foreign site or from most php sites in China. The first thing we need to do is to combine phplib and php3 to make it work. To achieve this, we need to install phplib first. It is easy to follow me (the following methods are 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 and session management, permission and database abstraction.
How to Use phplib to implement the session function?
1. First, unbind phplib. There is a directory named "php" in it, and copy the directory to the installation directory of apache. Take the author's machine as an example: My apache is installed in the d:/apache directory, and I copy the above "php" directory to d: a/pache, copy the files and directories under the pages directory under phplib to the d:/apache/htdocs directory. Note that the directory is not included. 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 the class library based on the actual situation of your machine. Change a program in the d:/apache/php/prepend. php3 file as follows:
If (! Isset ($ _ phplib) or! Is_array ($ _ phplib )){
$ _ Phplib ["libdir"] = "d:/apache/php/"; // change the path to the php Directory under phplib.
}
Modify the d:/apache/php/local. inc file as follows:
Class db_example extends db_ SQL {
Var $ host = "localhost"; // host name of your mysql database
Var $ database = "test"; // database Name
Var $ user = "root"; // database username
Var $ password = ""; // Database User password
}
In the final step, execute the create_database.mysql file in the stuff directory in the unlocked phplib directory to generate the initial table. Let's explain how phplib works. Every page using phplib must first find the class library file required 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, specify auto_prepend "d:/apache/php/prepend. after php3 "(with quotation marks), the pages will automatically contain the phplib class library. We can also add the directory of the phplib class library to the include variable to locate these files. Of course, the most benzene method is to specify the absolute path of phplib. This is not a good idea. portability is too bad!
Step 2: on every page using phplib, you must first call the page_open function for initialization. This will tell phplib that you will use status save now or in the future. A typical
An example of page_open is as follows:
<? Php
Page_open (array ("sess" => "example_session "));
?>
The array variable (sess) is used to initialize some state storage objects. Note: you must use the phplib built-in name (sess). These built-in names are stored in the local. as defined in 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 it, you should be able to think of the result. Haha, you have lost all your variables, but don't blame me for not telling you...
Because phplib uses cookies to store status 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 empty rows, if you find the error "oops-setcookie called after header has been sent", this indicates what is output to the browser before page_open (). Pay special attention to empty rows, because it is very difficult to find, the typical error is <? And? > Empty lines are output between tags. Check whether empty lines are included in the local. inc and prepend. php3 files. This is also a very error-prone place. To reduce the possibility of errors, we can write the initialization program as follows:
<?
Page_open (array ("sess" => "example_session "));
?>
<Html>
.....
</Html>
Step 3: Use it.
When a user accesses the website, the user's session starts. If the browser supports cookies, a session id will be created and put into the cookie, this unique id is randomly generated by php3 and then encrypted by md5 using a Random Seed string. The cookie here should be called session cookie, because the cookie is not written to the user's hard disk, when a session ends, the cookie is also completed. If the user's browser does not support cookies, the session id will be put into the url chain. Because the session id is encrypted, it is useless to steal the session. Session id stores user information, such as user authentication, authentication expiration time, user permissions, and other information you may need, which is convenient for us to use. A session is a user's session process. Session is not just used to track user registration. In fact, it can also be used in other scenarios. You can use it to store any information you want to store, this information can be used in subsequent pages, provided that phplib is used for those pages. The method is simple. After registering a variable, you can use it on the subsequent page until the session ends. Method:
<? Php $ sess-> register ("variable_name");?>
Note: Here, variable_name is not a variable value, but a variable name. You can specify a variable name before assigning a value. You can change the value of a variable on a page, and then access the variable on the page to get the changed value. Variable types are diverse. They can be a string, a number, and an array. For example:
Page 1:
<? Php
Page_open (array ("sess" => "example_session "));
$ Sess-> register ("first"); // note that you do not need to add $
If (iset ($ firstname )){
$ First = $ firstname;
}
.....
Page_close ();
?>
Page 2:
<? Php
Page_open (); // start session
Echo $ first; // check the effect
Page_close (); // Save the 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 variable will not be written back to the database and unpredictable consequences will occur. When the variable is used up 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 ();
?>
Phplib 7.0 uses a storage structure that allows you to store session data to databases, shared memory, or ldap. Phplib uses database classes, which gives you more options. 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 view online documents on its website. It's home in http://phplib.netuse.de/index.php3. The session Implementation of php4 is mostly learned from phplib. It also uses cookies to save session IDs and uses the file system to save variables (by default ). Therefore, its session variable cannot save objects (in fact, it can save the object content, but it does not make sense, because it is saved on a disk, not a live object, at best, it is the object body .) However, this limit is not too large. 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, the session configuration option is also added to the php. ini file because it supports more sessions than php3. Let's take a look at the functions and meanings of each item:
[Session]
Session. save_handler = files; handler used to store/retrieve data (when to save session variables, files are used by default)
Session. save_path = c:/temp; argument passed to save_handler)
; In the case of files, this is
; Path where data files are stored
Session. use_cookies = 1; whether to use cookies (whether to use cookies, of course, there is no choice in win)
Session. name = phpsessid
; Name of the session (the cookie name used by the default session. Do not change it)
; Is used as cookie name
Session. auto_start = 0; initialize session on request startup (whether to enable the session automatically. If it is set to 1, you do not have to call the session_start () function on each page)
Session. cookie_lifetime = 0; lifetime in seconds of cookie (set the retention 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) (cookie valid path)
Session. cookie_domain =; the domain the cookie is valid for (cookie valid domain name)
Session. serialize_handler = php; handler used to serialize data (define the identifier of the serialized data. This function is only used in the wddx module or php. The default value is php)
; Php is the standard serializer of php
Session. gc_probability = 1; percentual probability that sets the processing probability of each temporary file start processing (gc, garbage collection. The default value is 1. )
; 'Bucket collect' process is started
; On every session initialization
Session. gc_maxlifetime = 1440; after this number of seconds, stored (set the number of seconds before the temporary file for saving 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 (determines whether to delete the session Code referring to the client. Sometimes it is set not to be deleted for security or other considerations. The default value is 0 .)
; Externally stored urls containing ids
Session. entropy_length = 0; how many bytes to read from the file (set the number of digits that the session reads from high-entropy resources. The default value is 0 .)
Session. entropy_file =; specified here to create the session id (set the session code to be created using an external high-entropy resource or file, for example,/dev/random or/dev/urandom on unix systems. )
; Session. entropy_length = 16
; Session. entropy_file =/dev/urandom
Session. cache_limiter = nocache; set to {nocache, private, public} to (set session buffer restrictions)
; Determine http caching aspects
Session. cache_expire = 180; document expires after n minutes (document validity period, in minutes)
On windows, php 4.01pl2 and earlier versions may encounter an error after session. save_path is set. This is a php bug and has been fixed in php4.01pl2 and later versions. If you use a previous version, you can set the session. set save_path ". /", or set it to"/temp ", and create a directory named temp under the current root directory where you place the php script (My php script is placed under d: apachehtdocs, then I create a directory named temp under the d: root directory ).
The session functions in php4 mainly include the following:
Session_start: Initialize the session, which must be called at the beginning of each page of the session.
Session_destroy: ends the session and calls it at the end of the session.
Session_name: name of the current session to be accessed.
Session_module_name: access the current session module.
Session_save_path: the current session path.
Session_id: access the current session ID.
Session_register: registers a new session variable.
Session_unregister: Delete the registered session variable.
Session_is_registered: Check whether the session variable is registered.
Session_decode: decodes session data.
Session_encode: session data encryption.
Generally, we only need to call three functions.
That is, sesssion_start (), session_register (), and session_is_registered ().
Call the session_start () function at the beginning of each page of the session,
A typical session page is as follows:
<? Session_start ()?>
<Html>
....
<Body>
<?
$ Var = "hello ";
Session_register ("var"); // register the $ var variable. Note that the $ symbol does not exist.
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 six functions. Of course, these functions do not need to be called, which is 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 to be passed to it are $ sess_path, which corresponds to the session. save_path option in your php. ini file; $ session_name, which corresponds to the session. name option in php. ini. For details about how they work, see the following example.
Sess_close ();
This function is called when the page ends and the session processing program needs to be closed. (Note: Do not confuse it with sess_destory. It is used to end the session)
Sess_read ($ key );
This function is used 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 or deserialize the data. If you don't know what this means, don't worry about it)
Note: serialization stores variables or objects in files when the program ends or needs to be executed.
The technology for transferring data into memory is different from the method for saving data only.
Sess_write ($ key, $ val );
This function is called when the session handler needs to save data, which often occurs when your program ends. It stores the data in the location where the sess_read ($ key) function can be used for retrieval next time.
Sess_destroy ($ key );
This function is required to destroy the session. It is responsible for deleting sessions and clearing the environment.
Sess_gc ($ maxlifetime );
This function is responsible for clearing fragments. In this case, it is responsible for deleting outdated session data. Session handlers occasionally call them.
Now we know the functions we provide.
The custom program can use the mysql database or dbm file to save session data. Depends on your needs.
If you decide to use mysql for support, you need to do the following:
First, create a sessions database in mysql and create a sessions table. Run your mysql client and run 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 in the session_mysql.php file to match the database settings on your machine.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.