Error during initialization php session full tutorial 1th/2 page

Source: Internet
Author: User
Tags mysql client php session php3 file random seed unique id
I. Overview of the SESSION
What session is, at first I also do not understand, non-professional dictionary translation for the Conference, the Conference period. Make a less appropriate metaphor.
(although inappropriate, 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
The user's information is logged through the session, so that the user is asked to provide the Web server with this identity
For example, we often ask 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 is not retained, it is not to let users on every page of the Web page to provide a user name and password.
Of course, the session is not only for the user authentication function, but also may be used in other aspects, we will mention later. The session is interpreted in Chinese as a conversation period. A session period begins when the user enters the URL of a site and ends when he leaves the site. The session was first seen in the Dynamic scripting language Active Server Pages, and its powerful feature was a statement that was not clear.
When PHP is still in version 3.0, the session is always painful. Although PHP has the performance of fast, flexible, powerful and other advantages, but because of the session of the problem, so many site development abandoned PHP, at least my boss think so. There were a lot of PHP free libraries that offered the option to implement the session on the PHP3, but all of them felt not authentic. It's like you're spending thousands of of dollars on a mobile phone but a very coarse grass bag, although the function is the same, but always feel awkward. The advent of PHP4 has given PHP a chance to roll over the session. Although its session implementation is not ideal (mainly in terms of efficiency), but it is its own implementation, and can be used in practice. Then what do we do with the session, you say for a long while, I do not use words, you do not have to sell paper suspicion. OK, let's see what the session is for: People who have made the site have this experience, in a page of the variable (in this chapter refers to server-side variables, the same below) is not available on the next page, although there are some ways to achieve, such as with form,urlstring, etc., But some of the users are inconvenient, even if the form is automatically submitted, but the delay in the current network conditions are 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 variables registered in the session 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 authentication, program status records, the parameters passed between pages.
Said it so half of the benefits, you have been tempted to do it, don't be happy, it also has shortcomings: it is a file saved variables (of course, although the efficiency is not high, though can be used in other ways, but very troublesome), can not save the object. In contrast, the session in the ASP can hold object variables and memory variables to hold session variables. But why we also choose PHP, hehe, why, you can see this chapter from the beginning of this book, presumably you should also understand, you do not understand, faint, you look at the beginning again, I guarantee you become a PHP expert ^_^.
How is the session implemented? Oh, you must think very advanced, I come to tell you its secret. If we just save the 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 it? implemented in session with a cookie. 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 requests the server, the session ID is also sent to the server, so that the server can identify who you are, It is also possible to identify the variable. This makes it easy to understand why the session sometimes fails. If you do not believe, you can try: on the IE "Tools" menu has the "Internet Options" menu, open and then select "Security", "Custom Level", the security settings in the "Allow use of each chat cookies" set to disable, and then see if the session can be used. That's clear! However, PHP4 can automatically check the status of cookies on the Linux/unix platform and automatically pass the session ID to the URL when the cookie is not available. This is the only advantage of it in terms of the session more than ASP.
Second, the realization of the session in php3,4
In PhP3 there is no session of this stuff, but we need, how to do? Don't worry, there are a lot of people who have done this for you, the most famous of which is to calculate the phplib. You can go abroad to download, you can download most of the domestic PHP site. The first thing we need to do is let Phplib and php3 combine to make it work. In order to achieve this function, we need to install Phplib first. Follow me, it's easy (the following method is passed on win2000+php3.0.16+apache1.3.12+phplib7.2c+mysql3.23.21 for Win32) Phplib most basic features include user authentication, session management , permissions, and abstraction of the database.
How to use Phplib to implement session function?
First, you will phplib untie, there is a directory called "PHP", the directory is copied 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 above "PHP" directory to D:a/pache, and Phplib under the pages directory under the file and the directory is copied to D:/apache/htdocs, Note that the directory itself is not taken. Phplib class Library needs to be initialized according to the system, you can modify the file, which contains some basic parameters, you can according to the actual situation of your machine to modify. 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/"; Here's where you put phplib down the path to the PHP directory
Then change the D:/apache/php/ 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 user name
var $password = "";//Database user password
The final step is to execute the create_database.mysql file under the stuff directory in the Phplib directory, generating the initial table. We explain how phplib works, each page that uses phplib must first find the class library file that runs Phplib, and we can set the Auto_prepend variable in Php3.ini to support it. The phplib bundle contains a prepend.php3 file that will automatically include the Phplib class library when the auto_prepend is specified with "D:/apache/php/prepend.php3" (quoted). We can also add the directory of the Phplib class library into the include variable so that these files can be found, of course, the most benzene way is to specify the absolute path of phplib, this is not a good idea, portability is poor!
In the second step, each page that uses phplib, you must first call the Page_open function to initialize. This will tell Phplib that you are going to use state saving now or in the future. A typical
Page_open examples are as follows:
Page_open (Array ("sess" = "example_session"));
The array variable (sess) is used to initialize some state-saving objects, note that you must use the Phplib built-in name (Sess), which is defined in Local.ini, and the Page_open function must be called before the page content is output 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 store state information, the Page_open () function must be called before the page content is output to the browser, where the page content can be any HTML information or blank line, if you find the error "Oops-setcookie Called after the header has been sent ", which indicates what was output to the browser before Page_open (), you should pay special attention to the empty line, because it is very difficult to find, the typical error is in Blank lines are output between the tags, you should check to see if empty lines are included in the and prepend.php3 files, 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, specific use.
When a user visits the site, the user's session begins, and if the user's browser supports cookies, a session ID is placed into the cookie, and the unique ID is randomly generated by php3. And then using the random seed string for MD5 encryption, the cookie here should be called session cookie, because this cookie is not written to the user's hard drive, and when a session end, the cookie is also ended. If the user browser does not support cookies, then the ID of the session will be placed in the URL chain, because it is encrypted, so it is useless to steal. Session ID holds information about the user, such as user authentication, authentication expiry time, user rights, and other information you may need to facilitate our access. The session is actually the process of the user's sessions. The session is not just used to track the user's registration, in fact, it can also have other uses, you can use it to store any information you want to storage, this information can be used in the page that the user subsequently visited, of course, if those pages to use Phplib. The method is simple, register a variable and then use it on subsequent pages until the session ends. Method:
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 page, and the subsequent page access to the variable will have the value changed. The type of the variable is varied and can be a string, a number, an array. For example:
First page:
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 ();
Second page:
Page_open ();//Start session
echo $first;//Look at the effect
Page_close ();//Save state information
After registering a variable, each session variable is written back to the database when the page finally calls the Page_close () function. If you forget to call the Page_close () function, the variable will not be written back to the database, with unpredictable consequences. 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 ();
Phplib 7.0 uses a storage structure that allows you to store session data in a database, in shared memory, or in LDAP. Phplib uses a database class, which gives you more options, you can use Oracle8,mysql,postgresql and so on to save state information.
For other functions in phplib and for the use of other functions related to the session, you can refer to it with the manual or on its website to see the online documentation. It's home in HTTP://PHPLIB.NETUSE.DE/INDEX.PHP3. PHP4 's session implementation is mostly learned from Phplib, and it also relies on cookies to save the session ID and save the variable with the file system (by default). Therefore, its session variable cannot save the object (in fact, it can save the object content, but it has no meaning, because it is stored on disk, not live objects, at best, the body of the object. However, this limitation is not too large, we only need to save the variable in most cases. 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. The session configuration option is also available in the php.ini file because the session support is more than php3 in PHP4. Let's take a look at the roles and meanings of each:
Session.save_handler = files; Handler used to Store/retrieve data (save session variables by default, with files)
Session.save_path = c:/temp; Argument passed to Save_handler (the directory where the session variable is saved, under Linux/unix for/TMP, under win for your directory)
; In the case of files, 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) = Phpsessid
; Name of the session (the default session uses the cookie name, it is recommended not to change)
; is used as cookie name
Session.auto_start = 0; Initialize session on request startup (if session is automatically enabled, when 1 o'clock, you do not have to call the Session_Start () function on each page)
Session.cookie_lifetime = 0; Lifetime in seconds of cookies (sets the time, in seconds, to save the cookie after it is sent to the browser. The default value is 0, which is indicated until the browser is closed. )
; Or if 0, until browser is restarted
Session.cookie_path =/; The path the cookie is valid for (cookie) (valid path for cookies)
Session.cookie_domain =; The domain the cookie is valid for (a valid domain name for cookies)
Session.serialize_handler = PHP; Handler used to serialize data (defines the identity of the serialized figure, this feature is only used within the WDDX module or PHP. Default value is PHP)
; PHP is the standard serializer of PHP
session.gc_probability = 1; Percentual probability that the (set each temporary file to start processing (GC, garbage collection) processing probabilities. 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 if the session code referenced to the client is to be deleted.) Sometimes when safety or other considerations are taken, the settings are not deleted. 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 bits that the session reads from a high-entropy resource. The default value is 0.)
Session.entropy_file =; Specified here to create the session ID (set when the session code is established, use an external high-entropy resource or file to build, such as a/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 (documentation validity, in minutes)
In the Windows platform, the previous version of PHP4.01PL2 will appear after setting Session.save_path error, this is a PHP bug, PHP4.01PL2 and later has been fixed. If you use a previous version, you can set the Session.save_path to "./" or "/temp" and a directory named temp in the current packing directory where you put the PHP script (my php script is under D:apachehtdocs, Then I build a directory for temp in the D: Packing directory).
The functions of the session in PHP4 mainly include the following:
Session_Start: Initializes the session and needs to be called at the beginning of each page of the session.
Session_destroy: End session, where you need to end the session.
Session_name: Access the current session name.
Session_module_name: Access the current session module.
Session_save_path: Accesses the current session path.
SESSION_ID: Access the current session ID number.
Session_register: Registers a new session variable.
Session_unregister: Delete the registered session variable.
session_is_registered: Check if the session variable is registered.
Session_decode:session data decoding.
Session_encode:session data encryption.
Normally we only need to call three functions.
i.e. Sesssion_start (), Session_register (), session_is_registered ().
Call the Session_Start () function at the beginning of each page that needs to be used for the session.
A typical page that uses the session is as follows:


$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!";
echo "Sorry, not yet registered!";

Customization of Session processing in PHP4
We need to expand 6 functions, of course, these functions do not need you to call, for us is transparent.
These are the following functions:
Sess_open ($sess _path, $session _name);
This function is used 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 See the example below for details on how they work.
Sess_close ();
This function is called when the page finishes executing and 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 identified as $key. (Note: You don't have to worry about how to serialize and deserialize data if you don't know what it means, don't worry about it)
Translator Note: Serialization is to save a variable or object in a file at the end of the program or when needed, and then when the next time the program runs or needs
The technology that is transferred into memory is different from the method that only saves the 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 needed 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 the fragments. In this case, it is responsible for deleting obsolete session data. Session handlers occasionally invoke them.
Now we have a clear idea of the functions we provide.
Custom programs can save session data with MySQL database or dbm files. Depends on your needs.
If you decide to use MySQL for support, the following work is required:
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 $sess_db* variable of the session_mysql.php file to match the database settings on your machine.

Current 1/2 Page 12 next page

The above describes the error during initialization php session full tutorial 1th/2 page, including the error during initialization aspects of the content, I hope to be interested in PHP tutorial friends helpful.

  • 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: 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.