SESSION full tutorial (2)
Publisher PHP 2004-12-01 15:45 Second, the implementation of session in PHP3, 4 is in PHP3, there is no session this kind of Dongdong, but we need, what should I do? Don't worry, many people have done these for you, the most famous of this is PHPLIB. You can go abroad to download, you can download in China's PHP site. The first thing we have to do is letting PHPLIB and PHP3 together make it work. In order to achieve this function, we need to install phplib first. Follow me, it is easy (the following method is in Win2000 PHP3.0.16 Apache1.3.12 phplib7.2c mysql3.23.21 for Win32) PHPLIB's most basic feature includes user authentication, session management, permissions, database Abstract. How to use phpo to implement the session function? First, first of all you unlock the phplib, there is a directory called "PHP", copy this directory to the Apache installation directory. Taking 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 copy the files and directories under the PHPLIB to the directory to D: / apache / htdocs, pay attention to the directory itself. PHPLIB class library needs to be initialized according to the system, you can modify the local.inc file, which contain some basic parameters, you can modify it according to the actual situation of your machine. Change a program in D: /Apache/php/prepend.php3 file is made as follows: if (! Isset ($ _ phpo) or! Is_ARRAY ($ _ phplib)) {$ _phplib ["libdir"] = "D: / Apache / PHP / "; // This changed to you PHPLIB's PHP directory path} and change the d: /apache/php/local.inc file as follows: Class DB_EXAMPLE EXTENDS DB_SQL {var $ host =" localhost "; / / Your MySQL database The host name var $ database = "test"; // Database name var $ user = "root"; // Database Username VAR $ Password = ""; // Database User Password} The last step The CREATE_DATABASE.MYSQL file under the stuff directory in the PHPLIB directory generates the initial table. We explain the PHPLIB's working principle. Each page that uses PHPLIB must first find a library file that runs PHPLIB, we can set the auto_prepend variable in php3.ini to support, the phplib distribution package contains a prepend.php3 file, After specifying auto_prepend, "D: /APACHE/PHP/Prepend.php3" (with quotation marks), each page will automatically include the phplib class library, we can also add the directory where the phplib class library is in the include variable so that you can find these Document, of course, the highestbenzene approach is to specify the absolute path of phplib. This is not a good idea, the portability is too bad! In the second step, each of the PHPLIB is used, you must first call the Page_Open function to initialize. This will tell PHPLIB, you will save the status or in the future.
A typical page_open example is as follows: Php page_open (Array "));>> Array Variable (sess) is used to initialize some status saving objects, note: PHPLIB is used (SESS) These internal names are that you are defined in local.ini, and the page_open function must be called before the page content is output to the browser. The PHP3 script will finally end in page_close (), which will write the relevant status data back to the database. If you forget, you should be able to think, haha, your variable is all lost, but don't blame I not tell you. ... 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 page content here can be any HTML information or blank line, if you find the error "OOPS - SetCookie Called After Header Has Been Sent, this indicates what is 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 between And?> Tags Output space line, you should check if you contain a space line in the local.inc and prepend.php3 files, which is also a very easy error. In order to reduce the possibility of error, we can write initialization programs like this: Page_open (array ("sess"));?> ..... html> third step, specific use . When a user accesses the site, the user's session begins. If the user's browser supports cookie, the ID will be created in the cookie, which is randomly generated by PHP3, and then use The random seed string is over-encrypted, and the cookie here should be called session cookie, because this cookie is not written in the user's hard drive, and the cookie is also ended when an SESSION period ends. If the user browser does not support cookie, then the session ID will be placed in the URL chain because it is encrypted, so it is useless. The session ID stores information about the user, such as the user's authenticated, authenticated expiration time, user permissions, and other information you may need, so that we will take us. The session is actually the process of user a session. Session is not only used to track the registration of the user. In fact, it can have other use sites, you can use it to store any information you want to store, which can be sent in the page subsequently accessed. Infringing, of course, the premise is those pages to use phpo. The method is simple. After registering a variable, you can use it in the subsequent page until the end of the session. Method: Php $ sess-> register ("Variable_Name");?> Note that the variable_name here is not a variable, but the variable name, you can specify the variable name, then assign the value. You can change the value of the variable in a page, and subsequent pages access the variable will get the value after changing. The type of variable is diverse, can be a string, a number, an array.
For example: Page: Php page_open (array ("sess")); $ sess-> register ("first"); // Note that the variable is not need to add $ IF (ISET $ firstname)) {$ first = $ firstname;} ..... Page_close ();?> Page II: php page_open (); // Start session echo $ first; // Look at the effect Page_Close () ; // Save status information?> Register a variable, after the page is finally called, 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, which will appear unpredictable consequences. When the variable is used, you no longer need to use it, you can call the following function to delete the variable: Php page_open ("sess")); ... $ sess-> unregister (" Variable_name "); ... Page_close ();> PHPLIB 7.0, a storage structure is used, which allows you to store session data into the database, shared memory or LDAP. PHPLIB uses database classes, which makes you more choices, you can use Oracle8, MySQL, PostgreSQL, and the like to save status information. With regard to other features in phplib and other functions of the session, you can see the manual it belts, or on its website to see online documentation. Its hometown is in http://phplib.netuse.de/index.php3. PHP4's session implementation is mostly learned from phplib, which also rely on cookies to save the session ID, save variables with file system (by default). Therefore, its session variable cannot save objects (in fact saving object content, but there is no meaning because it is saved on disk, not living objects, is the amount of object is the object body.) But this limit 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 say how to save the session in the database. In PHP4, due to multiple session support than php3, there are also SESSION configuration options in the php.ini file.
Let's take a look at the roles and meaning of each: [session] session.save_handler = files; handler = files; Handler Used to store / retrieve data (using something saved) session.save_path = C: / TEMP; Argument passed to save_handler (Save the session variable, under Linux / UNIX / TMP, set to your directory in WIN); in the case of files, this is the; path where data files are stiled session.use_cookies = 1; WHETHER TO USE Cookies (Whether to use cookies, of course, no choice in Win) session.name = phpsessid; Name of the session (the cookies name used by default session); Is Used as cookie name session. Auto_Start = 0; Initialize Session on Request Startup (whether the session is automatically enabled, when 1, you can call the session_start () function in each page) session.cookie_lifetime = 0; Lifetime In Seconds Of cookie The saving time after the browser is second. The default is 0, indicating until the browser is turned off.); Or if 0, unsteil browser is restarted session.cookie_path = /; the path the cookie is valid for (cookie) (cookies effective path) session.cookie_domain =; the domain the cookie is valid for (cookies valid domain name) session.serialize_handler = php; handler use to serialize data (Define the identity of serialized data, this function is only WDD X Module or PHP internal use. The default value is PHP); php is the standard serializer of php session.gc_probability = 1; Percentual Probability That That The (GC, GARBAGE Collection) Processing probability. The default is 1.); 'garbage collection' process is started; on every session initialization session.gc_maxlifetime = 1440; after this number of seconds, stored (survival number of seconds before the session is set to save the temporary file is cleared); data will be seen as 'garbage' And; cleaned up by the gc process session.referer_check =; check http referer to invalidate (decide if the session code of the client is to be deleted. Sometimes it is not deleted when safe or other considerations. The default is 0.
); Externally stiled urls containing IDS session.entropy_length = 0; How many bytes to read from the file (Set the number of bits read from the high entropy "resource. The default is 0.) session.entropy_file =; specified here To create the session ID (Setting the session code is established, use external high entropy resources or files to create, such as / dev / random or / dev / urandom on the UNIX system.); session.entropy_length = 16; session.entropy_file = / dev / urandom session.cache_limiter = nocache; set to {nocache, private, public} to (the buffering limit setting session); determine HTTP caching aspects session.cache_expire = 180; document expires after n minutes (the document is valid, the unit is Minute under the Windows platform, the previous version of PHP4.01PL2 appears in the event of session.save_path, this is a bug of PHP, in PHP4.01PL2 and later have been fixed. If you use the previous version, you can set the session.save_path to "./", or set to "/ Temp" and build a directory named TEMP in the current disk of the PHP script ( My PHP script is placed under D: apachehtdocs, then I will build a directory for TEMP in the D: Plate directory). The function on the session in PHP4 mainly has the following: session_start: Initialization Session, you need to call each page of the Session. Session_Destroy: End Session and ending the session in need. 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 a new session variable. Session_unregister: Delete the registered session variable. Session_is_register: Check if the session variable is registered. Session_Decode: session data decoding. Session_encode: session data encryption. Typically, we only need to call three functions. SESSSION_START (), session_register (), session_is_register ().
Call the session_start () function at the beginning of each page that needs to be used to session, a typical page of session as follows: Session_start ()?> ....
$ Var = "hello"; session_register ("var"); // Register $ VAR variable, note that there is no $ symbol IF (session_is_registered ("var") // check the variable registration Echo "Haha, register!"; else echo "Sorry , Have not registered! ";> Body> html> PHP4 Session Processing Customization We need to expand 6 functions, of course, these functions do not need you to call, it is transparent to us. These functions are: sess_open ($ sess_path, $ session_name); this function is called by the session handler to initialize. Two parameters that need to be passed are $ sess_path, which corresponds to the session.save_path option in your php.ini file; $ session_name, it corresponds to the session.name option in php.ini. How do they work, please see the example below. SESS_CLOSE (); This function is called at the end of the page and the session handler needs to be turned off. (Note, don't confuse the sess_destory, it is used to end the session) sess_read ($ key); this function is when the session handler reads 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 and reverse sequencing data, if you don't know what this means, don't worry about it) Translator Note: Serialization is the variable Or the object is saved in the file when the program ends or needs to run or need it in the next program, which is different from the method of only saving only the data. Sess_write ($ key, $ val); this letter data needs to be called when the SESSION handler needs to save data, which often occurs at the end of your program. It is responsible for saving the data next time you can retrieve in the SESS_READ ($ Key) function. SESS_DESTROY ($ key); this function is destroyed when you need to destroy the session. It is responsible for deleting the session and clears the environment. SESS_GC ($ MaxLiFetime); this function is responsible for cleaning the fragmentation. In this case, it is responsible for deleting outdated session data. The Session handler will occasionally call them. Now we have clearly appointed our function. Custom programs can save session data with a MySQL database or DBM file. Depending on your needs. If you decide to use MySQL 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 perform 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 session_mysql.php file $ The sess_db * variable makes it matches the database settings on your machine.
(Sorry, because of the copyright reason, I can't remove the following code, I have to add some comments ========================== ============================================================================================================================================================================================================= ===== / * ----------------------------------------- ------------------------------- * SESSION_MYSQL.PHP * -------------- -------------------------------------------------- -------- * php4 mysql session handler * Version 1.00 * by ying zhang (ying@zippydesign.com) * Last Modified: May 21 2000 * * -------------- -------------------------------------------------- -------- * Terms of usage: * ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ ----------------------------------- * You are free to use this library in Any Way you want, No Warranties Are * Expressed or Implied. this Works for Me, But I don't Guarantee That IT * WORKS for you, use at Your Own Risk. * * While Not Required to Do So, I Would Appreciate IT if you would 10 This Header Information. if Make Any Modifications Or Improvements, * please send the via email to ying zhang
Sessions "Like So: * * Create Table Sessions (* SessKey Char (32) Not Null, * Expiry Int (11) Unsigned Not Null, * Value Text Not Null, * Primary Key (SESSKEY) *); * * --- -------------------------------------------------- ------------------- * Installation: * --------------------------- ------------------------------------------- * Make Sure You Have MySQL Support Compiled Into PHP4. THEN COPY THIS * SCRIPT TO A DIRECTORY THAS ISSIBLE BY THE REST OF Your PHP * Scripts. * Confident Your PHP4 has mysql support, then copy this script to the directory related to your PHP script. * ------------------------------------------------- ----------------------- * Usage: (Usage) * ------------------- -------------------------------------------------- --- * Include this file in your scripts before you call session_start (), you * don't have to do anything specialAfter That. * Include this file to the file you want to use, must call session_start () before Otherwise, * will be very miserable, don't blame me, I don't tell you. This doesn't need to do anything, and you will be the same as you used to use Session.
* / $ Sess_dbhost = "localhost"; / * Database Server hostname * / $ sess_dbname = "sessions"; / * database name * / $ sess_dbuser = "phpsession"; / * database user * / $ sess_dbpass = "phpsession"; / * database password * / $ SESS_DBH = ""; $ SESS_LIFE = get_cfg_var ( "session.gc_maxlifetime"); function sess_open ($ save_path, $ session_name) {global $ SESS_DBHOST, $ SESS_DBNAME, $ SESS_DBUSER, $ SESS_DBPASS, $ SESS_DBH; if ($ Sess_dbh = mysql_pconnect ($ sess_dbhost, $ sess_dbuser, $ sess_dbpass)) {echo "
} Function sess_destroy ($ key) {global $ SESS_DBH; $ qry = "DELETE FROM sessions WHERE sesskey = '$ key'"; $ qid = mysql_query ($ qry, $ SESS_DBH); return $ qid;} function sess_gc ($ maxlifetime ) {global $ SESS_DBH; $ qry = "DELETE FROM sessions WHERE expiry <" time ();. $ qid = mysql_query ($ qry, $ SESS_DBH); return mysql_affected_rows ($ SESS_DBH);} session_set_save_handler ( "sess_open", "sess_close "," Sess_read "," sess_write "," sess_destroy "," sess_gc ");?> ============================= ==================================== The interface when using DBM files is customized ======= ============================================================================================================================================================================================================= ======== / * -------------------------------------- ---------------------------------- * SESSION_DBM.PHP * ----------- -------------------------------------------------- ----------- * PHP4 DBM session Handler * Version 1.00 * by ying zhang (ying @
ZippyDesign.com) * Last Modified: May 21 2000 * * ------------------------------------- --------------------------------- * Terms of usage: * --------- -------------------------------------------------- ------------- * You are free to use this library in Any Way you want, no warranties are * expressed or Implied. This works for me, but I don't guarance That IT * Works for you, USE AT YOUR OWN RISK. * * While not required to do so, I would appreciate it if you would retain * this header information. If you make any modifications or improvements, * please send them via email to Ying Zhang
* / $ SESS_DBM = ""; $ SESS_LIFE = get_cfg_var ( "session.gc_maxlifetime"); function sess_open ($ save_path, $ session_name) {global $ SESS_DBM; $ SESS_DBM = dbmopen ( "$ save_path / $ session_name", "c" RETURN ($ sess_dbm);} function sess_close () {Global $ sess_dbm; dbmclose ($ sess_dbm); return true;} function sess_read ($ key) {global $ sess_dbm, $ sess_life; $ var = ""; IF $ TMP = DBMFETCH ($ sess_dbm, $ key)) {$ evires_at = Substr ($ TMP, 0, STRPOS ($ TMP, "│")); if ($ evires_at> time ()) {$ var = Substr ($ TMP, STRPOS ($ TMP, "│") 1);}} Return $ VAR;} Function Sess_Write ($ KEY, $ VAL) {Global $ sess_dbm, $ sess_life; dbmreplace ($ sess_dbm, $ key, time () . $ SESS_LIFE "│" $ val);. return true;} function sess_destroy ($ key) {global $ SESS_DBM; dbmdele ($ SESS_DBM, $ key); return true;} function sess_gc ($ maxlifetime) {global $ SESS_DBM $ Now = Time (); $ key = dbmfirstkey ($ sess_dbm); while ($ key) {if ($ TMP = DBMFETCH ($ sess_dbm, $ key)) { $ expires_at = Substr ($ TMP, 0, STRPOS ($ TMP, "│")); if ($ now> $ expires_at) {sess_destroy ($ key);}}} $ key = dbmnextKey ($ sess_dbm, $ key); }}}} Session_set_save_handler ("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc");?> =================== =====================================
========== How to use it, because these functions are called PHP engines, regardless of us. We only need to pass the above configuration, you are using or the previous session function.
Take a look at the following code :) Session custom test code =================================== ======================================= / * --------------- -------------------------------------------------- ------- * Test.php * -------------------------------------- ---------------------------------- * PHP4 Customer Session Handler Test Script * Version 1.00 * by ying zhang (ying @ zippydesign.com) * Last Modified: May 21 2000 * / / / * Default to dbm handler * / if (! isset ($ handler) {$ handler = "dbm";} / * default action is increment * / IF ( ! isset ($ action)) {$ action = "increment";} / * loading script, depending on the handler * / if ($ handler == "dbm") {include ("session_dbm.php") {incrude ("session_dbm.php" } Elseif ($ handler == "mysql") {include ("session_mysql.php");} else {echo "