documentation-3.html
来自「PHPLOB注释详细版 使用模板技术的好帮手 PHP最有用的东东了」· HTML 代码 · 共 1,596 行 · 第 1/5 页
HTML
1,596 行
<P><P>You may define <CODE>$sess->auto_init</CODE> to the name of an includefile in your extension of session. Per convention, the name<CODE>setup.inc</CODE> is being used.<P><BLOCKQUOTE><CODE><HR><PRE>class My_Session extends Session { var $classname = "My_Session"; var $magic = "Calvin+Hobbes"; var $mode = "cookie"; var $gc_probability = 5; var $auto_init = "setup.inc"; // name of auto_init file.}</PRE><HR></CODE></BLOCKQUOTE><P>Whenever a new session is established, that is, a user without asession id connects to your application, the auto_init file isincluded and executed exactly once. The file is executed fromwithin the context of the <CODE>page_open()</CODE> function, that is,<EM>not</EM> within a global context. To define or access globalvariables from the auto_init file, you have to <CODE>global</CODE> them.<P>When auto_init is being executed, all features of your pagealready exist and are available globally.That is, you can safely rely onthe existence of the <CODE>$sess</CODE>, <CODE>$auth</CODE>, <CODE>$perm</CODE> and<CODE>$user</CODE> variables, if your application specifies them.<EM>Note</EM> that you cannot in general know which particular pagetriggered the execution of auto_init, though. If you have somepages that request authentication and others that don't, youcannot rely on the presence of the <CODE>$auth</CODE> object in general,but have to test for it with <CODE>is_object($auth)</CODE> beforeaccessing it.<P>The auto_init file is the appropriate place to initialize andregister all your session variables. A sample <CODE>setup.inc</CODE> maylook like this:<P><BLOCKQUOTE><CODE><HR><PRE><?phpglobal $lang; // application language$lang = "de"; // german by default$sess->register("lang");global $cur; // application currency$cur = "EUR"; // Euro by default$sess->register("cur");global $cart;$cart = new Shop_Cart; // Create a shopping cart object as defined in local.inc$sess->register("cart"); // register it.?></PRE><HR></CODE></BLOCKQUOTE><P><EM>Note:</EM> If you don't use a fallback_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 <CODE>setup.inc</CODE> for each pagethey visit, too. Nothing can be done about this.<P><H3>Unregistering variables and deleting sessions</H3><P>To get rid of a persistent variable, call<CODE>$sess->unregister()</CODE> 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.<P>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 <CODE>$sess->delete()</CODE>. 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.<P><BLOCKQUOTE><CODE><HR><PRE><?php page_open(array("sess" => "Shop_Session")); // send order as mail mail_order($shopowner, $user, $cart); // delete the current session $sess->delete(); // now get a new session id, but retain the users // address and name: page_open(array("sess" => "Shop_Session")); // will force auto_init again! $sess->register("user"); // could be done in auto_init as well?></PRE><HR></CODE></BLOCKQUOTE><P><H3>Reading and understanding session data for debugging</H3><P>When debugging PHPLIB applications, it is often useful to beable to read and understand the contents of the active_sessionstable. Each session is represented by a single line in thistable. The primary key to this table is the pair <CODE>name</CODE> and<CODE>sid</CODE>. <CODE>name</CODE> is the content of <CODE>$this->name</CODE> andis usually the classname of your session class. <CODE>sid</CODE> is thecontent of <CODE>$this->id</CODE> and is usually the MD5 hash of auniqid and some magic string.<P>By choosing a pair, it is possible for PHPLIB to have more thanone session type (for example, session and user data, see the<CODE>User</CODE> class below) per application and store all this datain a single table. If you are debugging a session class, forexample <CODE>Example_Session</CODE>, only records where <CODE>name ="Example_Session"</CODE> are of interest to you. Determine the currentsession id of your <CODE>Example_Session</CODE> by printing <CODE>$sess->id</CODE>and select the record with that <CODE>name</CODE> and <CODE>sid</CODE> from thedatabase.<P>The <CODE>changed</CODE> field indicates when this record has beenupdated the last time. It is a 14 character (Y2K compliant)string of the format YYYYMMDDhhmmss. Ordering by <CODE>changed</CODE>desc will show you the most current session records first (theMySQL "limit" clause may come in handy here).<P>The <CODE>val</CODE> column of a session record contains a PHP programthat can be safely fed to <CODE>stripslashes()</CODE> first and<CODE>eval()</CODE> 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.<P>First item is always an assignment to <CODE>$this->in</CODE>. If setto 1, auto_init has been executed by this session. If<EM>not</EM> set to 1, auto_init has not been executed, yet.This may be because no auto_init file is defined forthat session.<P>After that comes code like this: <CODE>$this->pt = array();</CODE>followed by a bunch of assignments like<CODE>$this->pt["somestring"] = 1;</CODE>. Each somestring is thename of a registered variable. Variable registrations arepersistent themselves and are saved with the <CODE>$this->pt</CODE>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.<P>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<CODE>$GLOBALS[somevar] = "value";</CODE>. <P>For an array, first <CODE>$GLOBALS[someary] = array();</CODE>is generated. Then the scalars that make up the array, if any,are written out, generating code that looks like<CODE>$GLOBALS[someary][index] = "value"</CODE>.<P>And for objects, code to create an object instance is saved:<CODE>$GLOBALS[someobj] = new Classname;</CODE>. "Classname"is taken from the objects <CODE>$classname</CODE> slot, which <EM>must</EM>be present and accurate. Then the scalars that are to be savedare written out, according to the contents of the objects<CODE>persistent_slots</CODE> array:<CODE>$GLOBALS[someobj]->slot = "value";</CODE> is written.<P>If you want to see what values have been saved to thedatabase, you just have to look at the <CODE>$GLOBALS</CODE> assignmentsfor that session.<P><H3>How "serialize()" operates</H3><P><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.<P>The heart of the session class is the <CODE>serialize()</CODE> 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 <CODE>$GLOBALS["a"]</CODE> and the global variable <CODE>$a</CODE>has the value <CODE>17</CODE>, then serialize will create the PHPprogram <CODE>$GLOBALS["a"] = "17";</CODE>. To save memory,<CODE>serialize()</CODE> operates on a reference parameter <CODE>$str</CODE>,where is will append the code generated.<P>First thing <CODE>serialize()</CODE> does is to determine the type ofthe current expression using the PHP <CODE>gettype()</CODE> function.The current type is stored in <CODE>$t</CODE>. The type of theexpression may indicate either a scalar value (integer number,float number or string), an array or an object.<P>Scalar values are the easiest to handle: <CODE>serialize()</CODE> justevaluates the current expression and remembers the result valuein <CODE>$l</CODE>. 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, <CODE>serialize()</CODE> ends here forscalars.<P>In the case of <CODE>$t</CODE> indicating an array, code is generated tocreate an empty array (<CODE>expression = array();</CODE>). Then thekeys of current expression are enumerated and for each key<CODE>serialize()</CODE> is called recursively with the current keyappended to the expression. That will append code for each arrayslot.<P>Should <CODE>$t</CODE> indicate an object, code is generated to createthat object (<CODE>expression = new Classname;</CODE>). Since one cannotfind out the name of the class of an object for arbitraryobjects in PHP, objects handled by <CODE>serialize()</CODE> must have aslot named <CODE>classname</CODE>. The object handler will thenenumerate the contents of the objects slot <CODE>persistent_slots</CODE>and call <CODE>serialize()</CODE> recursively for each of these slotswith the appropriate prefix.<P>Since many of the expressions used in <CODE>serialize()</CODE> requirevariable variable names or even variable code, <CODE>eval()</CODE> isused liberally. Unfortunately, this makes the code hard to read.<P><H2><A NAME="ss3.9">3.9 Auth</A></H2><P><P>Authentication management can be used to authenticate a session,that is, to identify the user at the client side of the session.<P>Authentication is done inline, with HTML forms, <EM>not</EM> withHTTP authentication (that's the browser popup you get when youhit a page protected with htaccess). Inline authentication hasseveral advantages over HTTP authentication:<P><UL><LI>It can be undone: A session can be un-authenticated, theuser can "log out".</LI><LI>It can expire: A session can automatically beun-authenticated after a given idle time.</LI><LI>It can be customized: You are not limited to user/passwordpairs. Instead you could use a customer number, operator idand a password to log in. Also, you have full control overthe login screen, which is a normal HTML page with logos,help and forms as you see fit.</LI><LI>It is database based. Authentication is being done againsta database of your design, not a htpasswd text file.</LI><LI>It is per page. You decide on a per-page basis which pagesare authenticated and which aren't.</LI><LI>It can be user authenticating and optionally selfregistering. In <EM>registration</EM> mode, a user without a valid login isencouraged to register and an account is created for thisuser.</LI><LI>It works with CGI PHP. HTTP authentication is availableonly in mod_php.</LI><LI>It is integrated with a permission checking scheme.</LI></UL><P><H3>Instance variables</H3><P><P><CENTER><TABLE BORDER><TR><TD><BR>classname</TD><TD>Serialization helper: The name of this class.</TD></TR><TR><TD>persistent_slots</TD><TD>Serialization helper: The names of all persistent slots.</TD></TR><TR><TD>lifetime</TD><TD>Maximum allowed idle time before the authentication expires. If set to 0, The authentication never expires (as long as the session remains active).</TD></TR><TR><TD>refresh</TD><TD>Maximum allowed time before the authentication info (perms and alike) are re-read from the database calling <CODE>auth_refreshlogin()</CODE> method. If set to 0 authentication info are read only at the login stage.</TD></TR><TR><TD>mode</TD><TD>Authentication mode: <CODE>log</CODE> or <CODE>reg</CODE> (see below).</TD></TR><TR><TD>database_class</TD><TD>A classname. Auth uses this class to make a database connection.</TD></TR><TR><TD>database_table</TD><TD>Database table used to keep the session variables.</TD></TR><TR><TD>magic</TD><TD>An arbitrary value used in uniqid generation.</TD></TR><TR><TD>nobody</TD><TD>Flag: If true, we use default authentication.</TD></TR><TR><TD>cancel login</TD><TD>The name of a button that can be used to cancel a login form</TD></TR><TR><TD><CAPTION>Accessible instance variables.</CAPTION></TD></TR></TABLE></CENTER><P><CENTER><TABLE BORDER><TR><TD><BR>db</TD><TD>Internal: The database connection object instance.</TD></TR><TR><TD>auth</TD><TD>Internal: User authentication information, see below.</TD></TR><TR><TD>in</TD><TD>Internal: Used in default authentication mode.</TD></TR><TR><TD><CAPTION>Internal instance variables.</CAPTION></TD></TR></TABLE></CENTER><P><H3>Instance methods</H3><P><P><H3>Accessible instance methods</H3><P><P><DL><DT><B>url()</B><DD><P> A function that can be used in <CODE>auth_loginform()</CODE>a and<CODE>auth_registerform</CODE>. It returns the appropriate "action="attribute to the form tag.<P><DT><B>purl()</B><DD><P> A function that can be used in <CODE>auth_loginform()</CODE>a and<CODE>auth_registerform</CODE>. It prints the appropriate "action="attribute to the form tag.<P><DT><B>login_if($t)</B><DD><P>A function that can be used to change the current useridentity. See the section and example on using default authenticationbelow.<P><DT><B>unauth($nobody = false)</B><DD><P>This function destroys the authentication information in<CODE>$this->auth</CODE>, forcing the user to relogin the next timea protected page is being loaded.<P><CODE>$this->auth["uname"]</CODE> is being kept, so that thecorrect username is available as a default.<P>Since V6: To give the user the credentials of `nobody', passtrue as the first parameter to unauth. This will also change<CODE>$this->auth["uname"]</CODE>.<P>Since V7.2: Passing $nobody to this method is deprecated.<P><DT><B>logout($nobody = $this->nobody)</B><DD><P>This function destroy all authentication informationin <CODE>$this->auth</CODE>, forcing the user to reloginthe next time a protected page is being loaded.<P>Most applications want to use <CODE>$this->unauth()</CODE>instead.<P>Since V6: To give the user the credentials of `nobody', passtrue as the first parameter to logout. This defaults to the value you set in the class definition (<CODE>$nobody</CODE>).
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?