PHP session details

Source: Internet
Author: User
Tags php session
Session Details in PHP: this is a detailed page of session details in PHP. it introduces php, related knowledge, skills, experience, and some php source code.

Class = 'pingjiaf' frameborder = '0' src = 'http: // biancheng.dnbc?info/pingjia.php? Id = 324031 'Rolling = 'no'> Overview

Session refers to the time that a user spends browsing a website from entering the website to closing the browser. From the above definition, we can see that Session is actually a specific concept of time.

Generally, variables (server-side variables, the same below) on a page on a website cannot be used on the next page. with session, it is easy. The variables registered in the session can be used as global variables. In this way, the session can be used for user identity authentication, Program Status record, and parameter transfer between pages.

In PHP3, how does one implement session?

Php3 itself does not implement the session function. we can only implement it using other methods. The most famous one is phplib. Phplib's most basic functions include user authentication, Session management, permission and database abstraction. The following describes how to use phplib to implement a session.

1. install phplib first (the environment is win2000 php3.0.16 Apache1.3.12 phplib7.2c mysql3.23.21 for win32)

First, unbind phplib, which contains a "php" directory, and copy the directory to the Apache installation directory. For example, if Apache is installed under the d: \ Apache Directory, copy the "php" directory to the d: \ Apache Directory, and copy the pages directory of the phplib Directory (excluding the directory itself) copy the file and directory to d: \ Apache \ htdocs.

The phplib class library needs to be initialized based on the system. you may need to modify the local. inc file, which contains some basic parameters that can be modified based on the actual situation of your machine.

Change a program in the d: \ Apache \ php \ prepend. php file as follows:
If (! Isset ($ _ PHPLIB) or! Is_array ($ _ PHPLIB )){
$ _ PHPLIB ["libdir"] = "d:/Apache/php/"; // path of the php directory under phplib
}

Modify the d: \ Apache \ php \ local. inc file:
Class DB_Example extends DB_ SQL {
Var $ Host = "localhost"; // Host name of the mysql database
Var $ Database = "test"; // Database name
Var $ User = "root"; // database username
Var $ Password = "1234567"; // database user Password
}


Finally, the initial table is generated based on the create_database.mysql file in the stuff subdirectory under the phplib directory.

For every page using phplib, you must first find the class library file necessary to run phplib. the auto_prepend variable is set in ini. phplib contains a prepend. php file, and specify auto_prepend as "d:/Apache/php/prepend. php "(with quotation marks), the pages will automatically contain the phplib class library. we can also add the directory where the phplib class library is located to the include variable so that you can find these files.

2. call the page_open () function.

On every page that uses phplib, you must first call the page_open function for initialization. for example:

<? Php
Page_open (array ("sess" => "Test_Session "));
?>


The array variable (sess) is used to initialize some State-saving objects. Note that phplib built-in names (sess) must be used, which are defined in local. inc ..

Because phplib uses Cookies to save status information, the page_open () function must be called before the page content is output to the browser. The php script should end with page_close (), which will write the relevant status data back to the database; otherwise, the variable will be lost.

3. specific use.

Register a variable and use it on the subsequent page until the session ends. Method:

<? Php $ sess-> register ("varname");?>


Note that varname 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. Then, when you access the variable on the page, you will 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" => "Test _ Session "));
$ Sess-> register ("welcome"); // register the variable $ welcome. do not add $
$ Welcome = "Hello, PHP world! ";
......
Page_close ();
?>


Page 2:

<? Php
Page_open (); // start session
Echo $ welcome; // display the $ welcome defined on the first page
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 and no longer needed, you can call the following function to delete the variable:

<? Php
Page_open (array ("sess" => "Test _ Session "));
......
$ Sess-> unregister ("variable_name ");
......
Page_close ();
?>

In PHP4, how does one implement session?

The session id of php4 is saved by cookies and stored by the file system (by default). Therefore, its session variables cannot store objects. You can also save the session in the database.

There are many session functions in php4 (for details, refer to php. ini configuration). generally, we only need to call three functions: sesssion_start (), session_register (), and session_is_registered ().

Call the session_start () function at the beginning of each page of the session. for example:

<? Session_start ()?>
<Html> <body>
<?
$ Welcome = "hello world! ";
Session_register ("welcome"); // register the $ welcome variable. Note that the $ symbol does not exist.
If (session_is_registered ("welcome") // check whether the $ welcome variable is registered
Echo "welcome variable already registered! ";
Else
Echo "welcome variable is not registered yet! ";
?>
</Body>
Customization of session processing in php4

We need to expand six functions:
Sess_open ($ sess_path, $ session_name );
This function is called by the session handler for initialization.
The $ sess_path parameter corresponds to the session. save_path option in the php. ini file.
The $ session_name parameter corresponds to the session. name option in php. ini.

Sess_close ();
This function is called when the page ends and the session processing program needs to be closed.

Sess_read ($ key );
When the session handler reads the specified session key value ($ key), this function retrieves and returns session data identified as $ key. (Note: serialization is a technology that stores variables or objects in files when the program ends or needs to be stored. it is different from the method that only saves data when the next program runs or needs to be transferred to the memory .)

Sess_write ($ key, $ val );
This function is called when the session handler needs to save data, which often occurs when the 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.

The custom program can use the mysql database or DBM file to save session data, depending on the specific situation. To use mysql for support, perform the following steps:

First, create a sessions database in mysql and create a sessions table:

Mysql> create database sessions;
Mysql> GRANT select, insert, update, delete 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:

<?
$ SESS_DBHOST = "localhost";/* database host name */
$ SESS_DBNAME = "sessions";/* database name */
$ SESS_DBUSER = "phpsession";/* database username */
$ SESS_DBPASS = "phpsession";/* database password */
$ SESS_DBH = "";
$ SESS_LIFE = get_cfg_var ("session. gc_maxlifetime ");

...... // Custom functions

Session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc ");
?>


Custom interfaces for using dbm files:

<?
$ SESS_DBM = "";
$ SESS_LIFE = get_cfg_var ("session. gc_maxlifetime ");

...... // Custom functions

Session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc ");
?>


Test code customized by session:

<? Php
......
If ($ handler = "dbm") include ("session_dbm.php"); // the interface used
Elseif ($ handler = "mysql") include ("session_mysql.php ");
Else ......

Session_start ();
Session_register ("count ");
......
?>


In identity authentication, how does one apply Session?

Session can be used for user authentication:

Verify that the user is legal:

<?
Session_start ();
...... // Verification process
Session_register ("reguser ");
?>

On the other page, check whether the user is logged on.

<?
Session_start ();
If (isset ($ reguser) & $ reguser! = "") {// If you have logged on
Echo "Dear user, welcome ";
} Else {// If you have not logged on
Echo "please register first! ";
}
?>


User logout:

<?
Session_destroy ();
......
?>


How can I run multiple sessions concurrently?

Question: I wrote an invoicing system for my unit and found that multiple users need to be allowed to access a php application at the same time. The originally designed static and unique session ID causes Data confusion. In this way, it is imperative to dynamically generate a unique session ID.

The solution is simple: I used the php file name timestamp as the unique session ID, so that every session in my program will be unique and will not be confused.

I will publish my source code below to help you solve the same problem.

// Start a PHP session to preserve variables.
If (empty ($ mysessionname )){
$ Micro = microtime ();
$ Micro = str_replace ("", "", $ micro); // strip out the blanks
$ Micro = str_replace (".", "", $ micro); // strip out the periods
$ Mysessionname = "po_maint". $ micro;
}
Session_name ($ mysessionname );
Session_start ();


Program notes:

Use mysessionname as the unique sessionname between pages to pass variables. if you use this name, you must make a small change to the above program. Mysessionname cannot be the internal variable name of the session, because it already exists before the session starts. Mysessionname cannot be stored as a cookie, because multiple sessions will certainly overwrite the original cookie file. You can use an implicit form field to save it. In this way, no problem occurs.

More articles on "session details in PHP"

Love J2EE follow Java Michael Jackson video station JSON online tools

Http://biancheng.dnbcw.info/php/324031.html pageNo: 15.

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.