Home > Backend Development > PHP Tutorial > error during initialization session in php complete tutorial page 1/2

error during initialization session in php complete tutorial page 1/2

WBOY
Release: 2016-07-29 08:36:41
Original
1087 people have browsed it
1. Overview of session
What is session? I didn’t understand it at first. Non-professional dictionaries translate it as meeting, meeting period. Let’s make an inappropriate metaphor
(Although it is 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 he again provides a request to the web server in this capacity. For example, we often require users to log in on some websites, but how do we know that the user has logged in? Well, if there is no session, the login information cannot be retained, so why not require users to provide user names and passwords 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.
After talking about its benefits for so long, you are already tempted, don’t be happy yet, it also has shortcomings: it is a variable saved in a file (of course it is not efficient, although other methods can be used, but 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: In the "Tools" menu of IE, there is the "Internet Options" menu. 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, you unzip phplib. There is a directory called "php" in it. Copy this directory to the apache installation directory. 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 where you put 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 table. 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) is used to initialize some state saving objects. Note: You must use phplib built-in names (sess). These built-in names are defined in your 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 an error" oops - setcookie called after header has been sent", which 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 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"));
?>

.....

Step three, 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, and then It has been 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 string before the variable name Need to add $
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 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, 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();
?>
phplib 7.0 uses a storage 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 the manual it comes with, or go to its website to read the 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, and 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 name of the cookies 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 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, which 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 (definition 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 (Set the processing probability each time a temporary file starts processing (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 seconds to survive before the temporary file 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 (Determine whether the session code referring to the client should be deleted. Sometimes for security or other considerations, it will be set not Delete. 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 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 to create, use external high-entropy resources or files to create it, 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 (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. This is a bug in php. In php4 .01pl2 and later have been corrected. 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 the 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 using session is as follows:


....

$var="hello";
session_register("var");//Register the $var variable, note that there is no $ symbol
if(session_is_registered("var"))//Check the variable Register or not?
echo "haha, registered!";
else
echo "sorry, not registered yet!";
?>


Customization of session processing in php4
us Six functions need to be expanded. Of course, these functions do not need to be called by you and are transparent to us.
These functions are:
sess_open($sess_path, $session_name);
This function is called by the session handler for initialization 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 session.name option in php.ini. How exactly they work, please see the examples below.
sess_close();
This function is called when the page has finished executing and the session handler needs to be closed. (Note, not to be confused with sess_destory, which 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 the 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 The technology of saving variables or objects in a file when the program ends or when needed, and then transferring them into memory when the program is run or needed next time, is different from the method of only saving 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 saving the data in a place where it can be retrieved next time using the sess_read($key) function.
sess_destroy($key);
This function is used when the session needs to be destroyed. 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. Session handlers call them occasionally.
Now we have a clear idea of ​​the functions we provide.
The customized program 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 sessions database in mysql and create a sessions 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 step, modify the $sess_db* variables in the session_mysql.php file to match the database settings on your machine.

Current page 1/2 12Next page

The above introduces page 1/2 of the complete tutorial on error during initialization session in PHP, including the content of error during initialization. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template