⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 03-session.sgml

📁 PHPLOB注释详细版 使用模板技术的好帮手 PHP最有用的东东了
💻 SGML
📖 第 1 页 / 共 2 页
字号:
<sect2>Example<p>Use a subclass to provide the appropriate parameters to yoursession. Usually your subclass looks like this:<tscreen><code>class My&lowbar;Session extends Session {  var $classname = "My&lowbar;Session"; ## Persistence support    var $mode      = "cookie";  var $lifetime  = 0;            ## use session cookies    ## which container to use  var $that&lowbar;class = "Session&lowbar;sql";}</code></tscreen>Remember that you have to provide a <tt/DB&lowbar;Sql/ subclasswith the parameters needed to access your database.Use the page management functions (see above) to use yoursession subclass. The feature name for session management is<tt/sess/; provide the name of your session subclass as aparameter to the sess feature:<tscreen><code>  page&lowbar;open(array("sess" =&gt; "My&lowbar;Session"));</code></tscreen>Use the <tt/register()/ instance method to register variables aspersistent. If <tt/$sess/ is your session object, use<tscreen><code>$sess-&gt;register("s");</code></tscreen>to make the global variable <tt/$s/ persistent. <tt/$s/ may be ascalar value, an array or an object with persistence supportslots.Do not use the instance methods <tt/freeze()/ and <tt/thaw()/directly, but use the page management functions instead.To have some pages cached and others not cached, use multipleinstances of the session object. For example, for those pagesthat should be cached, use a session object instance like<tscreen><code>class My&lowbar;Cached&lowbar;Session extends My&lowbar;Session {  ## pages that use this session instance are cached.  var $allowcache = "private";}</code></tscreen>Be careful when using the <tt/public/ cache option. Publically cached pagesmay be accessible to unauthenticated users. The <tt/private/ cache optionprevents unauthenticated access, but is only functional in HTTP/1.1 browsers.<sect2>Using "auto&lowbar;init"<p>You may define <tt/$sess->auto&lowbar;init/ to the name of an includefile in your extension of session. Per convention, the name<tt/setup.inc/ is being used.<tscreen><code>class My&lowbar;Session extends Session {  var $classname = "My&lowbar;Session";  var $magic     = "Calvin+Hobbes";  var $mode      = "cookie";  var $gc&lowbar;probability = 5;  var $auto&lowbar;init = "setup.inc";   // name of auto&lowbar;init file.}</code></tscreen>Whenever a new session is established, that is, a user without asession id connects to your application, the auto&lowbar;init file isincluded and executed exactly once. The file is executed fromwithin the context of the <tt/page&lowbar;open()/ function, that is,<em/not/ within a global context. To define or access globalvariables from the auto&lowbar;init file, you have to <tt/global/ them.When auto&lowbar;init is being executed, all features of your pagealready exist and are available globally.That is, you can safely rely onthe existence of the <tt/$sess/, <tt/$auth/, <tt/$perm/ and<tt/$user/ variables, if your application specifies them.<em/Note/ that you cannot in general know which particular pagetriggered the execution of auto&lowbar;init, though. If you have somepages that request authentication and others that don't, youcannot rely on the presence of the <tt/$auth/ object in general,but have to test for it with <tt/is&lowbar;object($auth)/ beforeaccessing it.The auto&lowbar;init file is the appropriate place to initialize andregister all your session variables. A sample <tt/setup.inc/ maylook like this:<tscreen><code>&lt;?phpglobal $lang;   // application language$lang = "de";   // german by default$sess-&gt;register("lang");global $cur;   // application currency$cur = "EUR";   // Euro by default$sess-&gt;register("cur");global $cart;$cart = new Shop&lowbar;Cart;      // Create a shopping cart object as defined in local.inc$sess-&gt;register("cart"); // register it.?&gt;</code></tscreen><em/Note:/ If you don't use a fallback&lowbar;mode and you get usersthat turn off cookies, these users will force a new session eachtime they hit any page of your application. Of course this willforce inclusion and execution of <tt/setup.inc/ for each pagethey visit, too. Nothing can be done about this.<sect2>Unregistering variables and deleting sessions<p>To get rid of a persistent variable, call<tt/$sess-&gt;unregister()/ with the name of that variable. Thevalue of the formerly registered variable is still availableafter the call to unregister, but the variable is no longerpersistent and will be lost at the end of the current page.To get rid of all session related data including the sessionrecord in the database, the current session id and the sessioncookie in the users browser, call <tt/$sess-&gt;delete()/. Inshopping applications this is commonly done when the usercommits his order to get rid of the current shopping cart andeverything else. You may want to remember selected informationabout that user, though, as shown below.<tscreen><code>&lt;?php  page&lowbar;open(array("sess" =&gt; "Shop&lowbar;Session"));  // send order as mail  mail&lowbar;order($shopowner, $user, $cart);  // delete the current session  $sess->delete();  // now get a new session id, but retain the users  // address and name:  page&lowbar;open(array("sess" =&gt; "Shop&lowbar;Session")); // will force auto&lowbar;init again!  $sess->register("user");  // could be done in auto&lowbar;init as well?&gt;</code></tscreen><sect2>Reading and understanding session data for debugging<p>When debugging PHPLIB applications, it is often useful to beable to read and understand the contents of the active&lowbar;sessionstable. Each session is represented by a single line in thistable. The primary key to this table is the pair <tt/name/ and<tt/sid/. <tt/name/ is the content of <tt/$this-&gt;name/ andis usually the classname of your session class. <tt/sid/ is thecontent of <tt/$this-&gt;id/ and is usually the MD5 hash of auniqid and some magic string.By choosing a pair, it is possible for PHPLIB to have more thanone session type (for example, session and user data, see the<tt/User/ class below) per application and store all this datain a single table. If you are debugging a session class, forexample <tt/Example&lowbar;Session/, only records where <tt/name ="Example&lowbar;Session"/ are of interest to you. Determine the currentsession id of your <tt/Example&lowbar;Session/ by printing <tt/$sess->id/and select the record with that <tt/name/ and <tt/sid/ from thedatabase.The <tt/changed/ field indicates when this record has beenupdated the last time. It is a 14 character (Y2K compliant)string of the format YYYYMMDDhhmmss. Ordering by <tt/changed/desc will show you the most current session records first (theMySQL "limit" clause may come in handy here).The <tt/val/ column of a session record contains a PHP programthat can be safely fed to <tt/stripslashes()/ first and<tt/eval()/ after that. The PHP program consists entirely ofassignments and contains all instructions necessary to recreatethe persistent variables. The structure and order ofinstructions within this program is always the same.First item is always an assignment to <tt/$this-&gt;in/. If setto 1, auto&lowbar;init has been executed by this session. If<em/not/ set to 1, auto&lowbar;init has not been executed, yet.This may be because no auto&lowbar;init file is defined forthat session.After that comes code like this: <tt/$this-&gt;pt = array();/followed by a bunch of assignments like<tt/$this-&gt;pt["somestring"] = 1;/. Each somestring is thename of a registered variable. Variable registrations arepersistent themselves and are saved with the <tt/$this-&gt;pt/array. Even if the variable in question is not set, it may beregistered and stays so until it is unregistered or the sessionis deleted. Check the contents of the pt array is you want tosee which variables are currently registered with your session.Finally, the actual contents of your variables are saved. Thisis always done by accessing the $GLOBALS array and always byenumerating the scalar values that make up the persistentvariable. For a scalar, you will see code like<tt/$GLOBALS&lsqb;somevar&rsqb; = "value";/. For an array, first <tt/$GLOBALS&lsqb;someary&rsqb; = array();/is generated. Then the scalars that make up the array, if any,are written out, generating code that looks like<tt/$GLOBALS&lsqb;someary&rsqb;&lsqb;index&rsqb; = "value"/.And for objects, code to create an object instance is saved:<tt/$GLOBALS&lsqb;someobj&rsqb; = new Classname;/. "Classname"is taken from the objects <tt/$classname/ slot, which <em/must/be present and accurate. Then the scalars that are to be savedare written out, according to the contents of the objects<tt/persistent&lowbar;slots/ array:<tt/$GLOBALS&lsqb;someobj&rsqb;-&gt;slot = "value";/ is written.If you want to see what values have been saved to thedatabase, you just have to look at the <tt/$GLOBALS/ assignmentsfor that session.<sect2>How "serialize()" operates<p>The following information is applicable only to librarydevelopers, that is, programmers that want to change theinternal workings of PHPLIB. You may safely skip this section;some information here requires advanced understanding of the PHPlanguage.The heart of the session class is the <tt/serialize()/ internalfunction. This function takes an expression called prefix andgenerates PHP code that will assign the value of that expressionto the expression when executed. For example, if the expressionis <tt/$GLOBALS&lsqb;"a"&rsqb;/ and the global variable <tt/$a/has the value <tt/17/, then serialize will create the PHPprogram <tt/$GLOBALS&lsqb;"a"&rsqb; = "17";/. To save memory,<tt/serialize()/ operates on a reference parameter <tt/$str/,where is will append the code generated.First thing <tt/serialize()/ does is to determine the type ofthe current expression using the PHP <tt/gettype()/ function.The current type is stored in <tt/$t/. The type of theexpression may indicate either a scalar value (integer number,float number or string), an array or an object.Scalar values are the easiest to handle: <tt/serialize()/ justevaluates the current expression and remembers the result valuein <tt/$l/. An assignment is generated that will assign thecurrent value to the current expression. Since the current valuemay be a string and that string may contain bad characters (anyof backslash, double quotes or dollar sign), these charactersare backslashed. We are done, <tt/serialize()/ ends here forscalars.In the case of <tt/$t/ indicating an array, code is generated tocreate an empty array (<tt/expression = array();/). Then thekeys of current expression are enumerated and for each key<tt/serialize()/ is called recursively with the current keyappended to the expression. That will append code for each arrayslot.Should <tt/$t/ indicate an object, code is generated to createthat object (<tt/expression = new Classname;/). Since one cannotfind out the name of the class of an object for arbitraryobjects in PHP, objects handled by <tt/serialize()/ must have aslot named <tt/classname/. The object handler will thenenumerate the contents of the objects slot <tt/persistent&lowbar;slots/and call <tt/serialize()/ recursively for each of these slotswith the appropriate prefix.Since many of the expressions used in <tt/serialize()/ requirevariable variable names or even variable code, <tt/eval()/ isused liberally. Unfortunately, this makes the code hard to read.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -