Session complete Tutorial in PHP 1th/2 page _php Basics

Source: Internet
Author: User
Tags garbage collection md5 encryption session id mysql client php script php3 file random seed unique id
I. Overview of the SESSION
What is the session, just at the beginning I do not understand, the non-professional dictionary translation for the meeting, the meeting period. Make an inappropriate analogy.
(although not appropriate, but the meaning is the same), the session is the relationship between you and the site. Session plays a very important part in Web technology. Because a Web page is a stateless connection, you cannot know the user's browsing status. So we must
Record the user's information through the session so that the user can confirm the request to the Web server again in this capacity, for example
For example, we often require users to login in some sites, but how do we know that the user has logged in, if there is no session, the login information can not be retained, it is not to let users in every page of the page to provide user name and password.
Of course, the session is not only for the user identity authentication function, but also may be used in other aspects, we will mention later. Session in Chinese to explain is conversational period. A session period begins when the user enters a site's URL, and ends when he leaves the site. The session, which first appeared in the Dynamic scripting language Active Server Pages, is a powerful feature that cannot be clearly explained.
When PHP is still in the 3.0 version, session is its eternal pain. Although PHP has the implementation speed, the use of flexible, powerful and so on, but because of the session of the problem, so many site development gave up PHP, at least my boss thinks so. At that time, there are many PHP free function library to provide a session on the PHP3 program, but all make people feel not authentic. It's like you spend thousands of of dollars to buy a mobile phone but configure a very rough grass as a bag, although the function is the same, but always make people feel awkward. The advent of PHP4 has given PHP a chance to roll over on session issues. Although its session implementation is not very ideal (mainly the problem of efficiency), but it is realized by itself, and can be used in practice. Then we use the session to do, you said half a day, I do not use, you will not sell paper suspicion. OK, let's see what's the use of the session: People who have done the site have this experience, in a page of variables (in this chapter, the server-side variables, the same below) can not be used in the next page, although there are some ways to achieve, such as using form,urlstring and so on, But some are inconvenient for the user, even if the form is submitted automatically, but the delay in the current network conditions enough to suffocate, and both of these methods significantly increase the burden on the programmer. If you are developing a large project, these additional burdens cannot be overlooked. And with the session is good to do, the session of the registered variable can be used as a global variable. What, global variables? Great. In this way, you know what is the use of it: the most important for user identity authentication, program status records, the parameters of the transfer between pages.
said it so half-day benefits, you have been tempted to, do not happy, it has shortcomings: it is a file to save the variable (of course, not high efficiency, although can be used in other ways, but very troublesome), can not save objects. In contrast, the session in ASP can save the object variable and use the memory variable to save the session variable. But why we also choose PHP, Oh, why, you can see this chapter from the beginning of this book, you should also understand it, you do not understand, faint, you look from the beginning, I guarantee you to become a PHP expert ^_^.
How is the session implemented? Oh, you must think very advanced, I come to tell you its secret. If you only save variables, many readers understand that this is very simple, but as we said earlier, the HTTP protocol is a stateless connection, how do you know who the variable is, and whose is this variable? implemented in the session implementation with cookies. Cookies exist in the client, that is, the user's machine, which holds the user's session ID, which is the session number, when the user's browser request server, the session ID also sent to the server, so that the server can identify who you are, You can also identify the variable. So it's not hard to understand why the session sometimes fails. If you don't believe it, you can try it: on IE, the Tools menu has the Internet Options menu, open and then "security"-> "Custom Level", the security settings in the "Allow the use of each dialog cookies" set to disable, and then see if the session can be used. That's clear! However, PHP4 on the Linux/unix platform can automatically check the status of cookies, when the cookies are not available, the session ID will automatically be shipped with the URL to pass. This is the only advantage it has over ASP in terms of session.
The realization of session in php3,4
In PhP3 there is no session of this stuff, but we need, how to do? Don't worry, a lot of people do this for you, the most famous one is Phplib. You can go abroad to download, you can download most of the domestic PHP site. The first thing we have to do is get phplib and php3 together to make it work. In order to achieve this function, we need to first install Phplib. Follow me, it's easy (the following methods are passed on the win2000+php3.0.16+apache1.3.12+phplib7.2c+mysql3.23.21 for Win32) Phplib most basic functions include user authentication, session management , permissions and the abstraction of the database.
How to use Phplib to implement the session function?
First, you will phplib untie, there is a directory called "PHP", this directory copy to the Apache installation directory. Take the author's machine as an example: My Apache is installed in the D:/apache directory, I copy the "PHP" directory above to the D:a/pache, and copy the files and directories under Phplib under the pages directory to D:/apache/htdocs. Note that the directory itself is not taken. 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 procedure in the D:/apache/php/prepend.php3 file as follows:
if (!isset ($_phplib) or!is_array ($_phplib)) {
$_phplib["Libdir"] = "d:/apache/php/"; Here instead you put phplib the path of the PHP directory
}
The D:/apache/php/local.inc file is then changed as follows:
Class Db_example extends Db_sql {
var $host = "localhost";//your MySQL database host name
var $database = "Test";//Database name
var $user = "root";//Database user name
var $password = "";//Database user password
}
The final step is to perform the Create_database.mysql file in the stuff directory in the unpacked Phplib directory, generating the initial table. Let's explain how phplib works, every page that uses phplib must first find the class library file that runs Phplib, we can set the Auto_prepend variable to support in Php3.ini, A prepend.php3 file is included in the Phplib distribution, and the page automatically contains the Phplib class library when the auto_prepend is specified with the "d:/apache/php/prepend.php3" (quoted number). We can also add the Phplib Class Library directory into the include variable so that we can find these files, of course, the most benzene way is to specify phplib absolute path, this is not a good idea, portability is too bad!
In the second step, each page that uses phplib, you must first invoke the Page_open function for initialization. This will tell Phplib that you will use state saving now or in the future. A typical
Page_open examples are as follows:
<?php
Page_open (Array ("Sess" => "example_session"));
?>
The array variable (sess) is used to initialize some state-saving objects, noting that you must use the Phplib built-in name (Sess), which you define in Local.ini, and the Page_open function must be invoked before the page content is exported to the browser. PhP3 script should end with Page_close (), which will write the state data back to the database, if you forget, the result you should be able to think, haha, your variables are all lost, not to blame I didn't tell you ...
Because Phplib uses cookies to hold state information, the Page_open () function must be called before the page content is exported to the browser, where the page content can be any HTML information or a blank line, if you find the error "Oops-setcookie Called after header has been sent ", which indicates that the output to the browser before Page_open (), you have to pay special attention to the empty line, because it is very difficult to find, the typical error is in the.? And? > tags output blank lines, you should check whether the Local.inc and prepend.php3 file contains a blank line, which is also a very error-prone place. To reduce the likelihood of errors, we can write the initialization program like this:
?
Page_open (Array ("Sess" => "example_session"));
?>
.....
The third step, the concrete use.
When a user accesses the Web site, the user's session begins, and if the user's browser supports cookies, a session ID is placed in the cookie, and the unique ID is randomly generated by php3, And then using random seed strings for MD5 encryption, where the cookie should be called the session cookie, because the cookie is not written to the user's hard drive, when a session ends, the cookie is also completed. If the user's browser does not support cookies, then the session ID will be placed in the URL chain, because it is encrypted, so it is useless to steal it. The session ID holds information about the user, such as user authentication, authentication expiration, user rights, and other information you may need to facilitate our access. Session is actually the process of a user conversation. The session is not just for tracking the user's registration, but it can also have other uses where you can use it to store any information you want to save, which can be used in pages that the user subsequently accesses, assuming that those pages use Phplib. The method is simple enough to register a variable to use it on subsequent pages until the session ends. Method:
<?php $sess->register ("variable_name");?>
Note that the variable_name is not a variable value, but a variable name, and you can specify the variable name and then assign the value. You can change the value of a variable on a page, and the subsequent page accesses the variable to get the changed value. The types of variables are diverse, and can be a string, a number, an array. For example, Ming:
First page:
<?php
Page_open (Array ("Sess" => "example_session"));
$sess->register ("a"); Note that you do not need to add $ before the variable name
if (Iset ($firstname)) {
$first = $firstname;
}
.....
Page_close ();
?>
Second page:
<?php
Page_open ()/Start session
echo $first/See effect
Page_close ()//Save state information
?>
After registering a variable, when the page finally calls the Page_close () function, each session variable is 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 can have unpredictable consequences. When a 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 that allows you to store session data in a database, in shared memory, or in LDAP. Phplib uses database classes, which gives you more options, and you can use Oracle8,mysql,postgresql and so on to save state information.
For additional features in Phplib and the use of other functions related to sessions, you can refer to the manuals it brings, or to the online documentation on its website. It's home in HTTP://PHPLIB.NETUSE.DE/INDEX.PHP3. PHP4 's session implementation mostly from Phplib learned, it also relies on cookies to save the session ID, with the file system to save variables (by default). Therefore, its session variable cannot save the object (in fact, it can save the object's content, but it doesn't make sense because it is stored on disk, not a live object, at best, the object corpse.) However, this is not too restrictive, and in most cases we just need to save the variable. Of course you can also save the session in the database, and in the next section we'll talk about how to save the session in the database. There is more session support in PHP4 than PhP3, so there are also more session configuration options in php.ini files. Let's take a look at the role and significance of each of the following:
[Session]
Session.save_handler = files; Handler used to Store/retrieve data (save session variable with what, by default)
Session.save_path = c:/temp; Argument passed to Save_handler (save the directory for the session variable, under Linux/unix for/TMP, under win for your directory)
; In the case of files, this is the
; path where data files are stored
Session.use_cookies = 1; Whether to use cookies (whether cookies are used, of course, there is no choice under win)
Session.name = Phpsessid
; Name of the session (the name of the cookie that is used by default session, not recommended)
; is used as cookie name
Session.auto_start = 0; Initialize session on request startup (if session is automatically enabled, you do not have to call the Session_Start () function on every page when you are 1 o'clock)
Session.cookie_lifetime = 0; Lifetime in seconds of cookie (sets the time, in seconds, to save the cookie after it is sent to the browser.) The default value is 0, which means until the browser closes. )
; Or if 0, until browser is restarted
Session.cookie_path =/; The path the cookies are valid for (cookies) (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, which defines the identity of the serialized data, is used only within the WDDX module or PHP. The default value is PHP)
; PHP is the standard serializer of PHP
session.gc_probability = 1; Percentual probability that (set each temporary file to start processing (GC, garbage collection) processing probability. The default value is 1. )
; ' Garbage collection ' process is started
; On every session initialization
Session.gc_maxlifetime = 1440; After this number of seconds, stored (sets the surviving seconds before the temporary file that holds the session is purged)
; Data would be seen as ' garbage ' and
; Cleaned up by the GC process
Session.referer_check =; Check HTTP referer to invalidate (determines whether the session code referenced to the client is deleted.) Sometimes it is set to not delete when security or other considerations occur. The default value is 0. )
; Externally stored URLs containing IDs
session.entropy_length = 0; How many bytes to read from the file (sets the number of digits that the session reads from high entropy resources.) The default value is 0.)
Session.entropy_file =; Specified the session ID (set session code when setting up, use an external high entropy value resource or file to build, such as/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 (setting session buffering limit)
; Determine HTTP caching aspects
Session.cache_expire = 180; Document expires after n minutes (documents are valid for minutes)
Under the Windows platform, the previous version of PHP4.01PL2 will have an error after setting Session.save_path, which is a bug in PHP that has been modified PHP4.01PL2 and later. If you use the previous version, you can set Session.save_path to "./", or set to "/temp", and in the current packing directory where you put the PHP script to build a directory named temp (my php script is placed under D:apachehtdocs, Then I build a directory for temp in D: the packing directory.
The functions for session in PHP4 are mainly as follows:
Session_Start: Initializes the session, which needs to be invoked at the beginning of each page of the session.
Session_destroy: End session, at the end of the session to tune.
Session_name: Accesses the current session name.
Session_module_name: Accessing the current session module.
Session_save_path: Accesses the current session path.
SESSION_ID: Accesses the current session ID number.
Session_register: Registers a new session variable.
Session_unregister: Deletes the registered session variable.
Session_is_registered: Checks whether the session variable is registered.
Session_decode:session data decoding.
Session_encode:session data encryption.
Normally we just need to call three functions.
namely Sesssion_start (), Session_register (), session_is_registered ().
Call the Session_Start () function at the very beginning of each page where you need to use the session.
A typical page that uses the session is as follows:
<?session_start ()?>
....
<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 yet registered!";
?>
</body>
Customization of Session processing in PHP4
We need to expand 6 functions, of course these functions do not need you to call, is transparent to us.
The following functions are:
Sess_open ($sess _path, $session _name);
This function is called by the session handler to initialize the work. The two parameters that need 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 php.ini option in Session.name. How they work specifically, see the example below.
Sess_close ();
This function is invoked at the end of the page and when the session handler needs to be closed. (note, do not confuse with sess_destory, it is used to end the session)
Sess_read ($key);
This function is read when the session handler reads the specified session key value ($key).
This function retrieves and returns the session data that is identified as $key. (Note: You don't have to worry about serializing and deserializing data, if you don't know what it means, don't worry about it)
A serialization is a variable or object that is saved in a file at the end of the program or when it is needed, and then the next time the program runs or needs to
The technique of paging into memory differs from the method of saving only 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 your program. It is responsible for storing the data in the next place that can be retrieved using the Sess_read ($key) function.
Sess_destroy ($key);
This function is required 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 fragmentation. In this case, it is responsible for deleting obsolete session data. The session handler calls them occasionally.
Now we are clear about the functions we provide.
Custom programs can save session data in a MySQL database or dbm file. Depends on what you need.
If you decide to use MySQL for support, you need to do the following:
First we create a sessions database in MySQL and create a sessions table. Run your MySQL client first 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 (not NULL),
-> expiry int (one) unsigned NOT NULL,
-> value text NOT NULL,
-> primary KEY (Sesskey)
->);
Next, modify the session_mysql.php file's $sess_db* variable to match the database settings on your machine.
Current 1/2 page 12 Next read the full text
Related Article

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.