Home  >  Article  >  php教程  >  Detailed explanation of how to use session in PHP Page 2/2

Detailed explanation of how to use session in PHP Page 2/2

高洛峰
高洛峰Original
2016-12-24 09:27:491322browse

Detailed explanation of session in PHP 2

 Overview
 Session refers to the time that elapses from entering the website to closing the browser when the user browses a website, that is, the time the user spends browsing the website. From the above definition, we can see that Session is actually a specific time concept.
  Generally speaking, variables (referring to server-side variables, the same below) in a certain page on the website cannot be used in the next page. It is easy to handle with session. Variables registered in the session can be used as global variables. In this way, we can use session for user identity authentication, program status recording, and parameter transfer between pages.

  How is session implemented in the PHP3 version?
 PHP3 itself does not implement the session function. We can only use other methods to achieve it, the most famous of which is phplib. The most basic functions of phplib include user authentication, session management, permissions and database abstraction. Next we will describe how to use phplib to implement session.

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

 First unzip phplib, there is a "php" directory inside, copy this directory Go to the Apache installation directory. For example: Apache is installed in the d:Apache directory, then copy the "php" directory to d:Apache, and copy the files and directories in the pages directory of the phplib directory (excluding the directory itself) to d:Apachehtdocs.

 The phplib class library needs to be initialized according to the system, and the local.inc file may need to be modified, which contains some basic parameters, which can be modified according to the actual situation of your own machine.

 Change the program in the d:Apachephpprepend.php file to the following:

    if (!isset($_PHPLIB) or !is_array($_PHPLIB)) { 
      $_PHPLIB["libdir"] = "d:/Apache/php/"; //放phplib下php目录的路径 
    } 
  修改d:\Apache\php\local.inc文件: 
    class DB_Example extends DB_Sql { 
      var $Host = "localhost"; //mysql数据库所在主机名 
      var $Database = "test"; //数据库名 
      var $User = "root"; //数据库用户名 
      var $Password = "1234567"; //数据库用户密码 
    }

Finally, generate the initial table based on the create_database.mysql file in the stuff subdirectory under the phplib directory.
Since every page using phplib must first find the class library files necessary to run phplib, we can set the auto_prepend variable in php.ini to support it. phplib contains a prepend.php file and specify auto_prepend as "d :/Apache/php/prepend.php" (with quotes), 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 files can be found.

2. Call the page_open() function

In every page using phplib, you must first call the page_open function for initialization, for example:

  <?php 
  page_open(array("sess" => "Test_Session")); 
  ?>

Array variables (sess) are used to initialize some state saving objects. It should be noted here: You must use phplib built-in names (sess), which are defined in local.inc.
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 php script should end with page_close(), which will write the relevant status data back to the database, otherwise the variables will be lost.

 3. Specific use.

 After registering a variable, you can use it in subsequent pages until the session ends. Method:
  <?php $sess->register( "varname"); ?>
  Note that varname 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 on a certain page, and the changed value will be obtained when the variable is accessed on subsequent pages. The types of variables are diverse and can be a string, a number, or an array. To illustrate:
  First page:
  <?php
  page_open(array("sess" => "Test _Session"));
  $sess->register( "welcome"); //Register variable $welcome, note No need to add $
  $welcome="Hello, PHP world!";
  …
  page_close();
     
 Second page:
  <?php
  page_open();//Start session
  echo $welcome ; //Display the $welcome defined in the first page
 page_close();//Save 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 variables will not be written back to the database, which will have unpredictable consequences. 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(); 
    ?>

在PHP4版本中是如何实现session的? 

  php4的session也靠cookies保存session id,用文件系统保存变量(默认情况下),因此,它的session变量不能保存对象。当然也可以将session保存在数据库中。 
  在php4中有关session的函数很多(详见php.ini配置一文),通常情况下我们只需要调用三个函数即可:sesssion_start()、session_register()、session_is_registered()。 
  在需要用到session的每一页的最开始处调用session_start()函数, 例如: 
    <?session_start()?> 
    <html><body> 
    <? 
    $welcome="hello world !"; 
    session_register("welcome");//注册$welcome变量,注意没有$符号 
    if(session_is_registered("welcome"))//检查$welcome变量是否注册 
      echo "welcome变量已经注册了!"; 
    else 
      echo "welcome变量还没有注册!"; 
    ?> 
    </body></html> 
  php4中session处理的定制 
  我们需要扩充6个函数: 
    sess_open($sess_path, $session_name); 
    这个函数被session处理程序调用来作初始化工作。 
    参数$sess_path对应php.ini文件中的session.save_path选项 
    参数$session_name对应php.ini中的session.name 选项。 
    sess_close(); 
    这个函数在页面结束执行并且session处理程序需要关闭时被调用 
    sess_read($key); 
    这个函数在session处理程序读取指定session键值($key)时,检索并返回标识为$key的session数据.(注意:序列化是将变量或对象在程序结束或需要时保存在文件中,在下次程序运行或需要时再调入内存的技术,有别于只保存数据的方法。) 
    sess_write($key, $val); 
    这个函数据在session处理程序需要将数据保存时调用,这种情况经常在程序结束时发生。它负责将数据保存在下次能用sess_read($key)函数检索的地方。 
    sess_destroy($key); 
    这个函数在需要消毁session时。它负责删除session并且清除环境。 
    sess_gc($maxlifetime); 
    这个函数负责清理碎片。在这种情况下,它负责删除过时的session数据。session处理程序会偶尔调用它们。 
  定制程序可以用mysql数据库或DBM文件保存session数据,视具体的情况而定。如果使用mysql作支持,那还需要进行以下的步骤: 
  首先在mysql中创建一个sessions数据库,并且创建一个sessions表: 
  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) 
    -> ); 
  下一步,修改session_mysql.php文件的$SESS_DB* 变量使其匹配你机器上的数据库设置: 
<? 
$SESS_DBHOST = "localhost"; /* 数据库主机名 */ 
$SESS_DBNAME = "sessions"; /* 数据库名 */ 
$SESS_DBUSER = "phpsession"; /* 数据库用户名 */ 
$SESS_DBPASS = "phpsession"; /* 数据库密码 */ 
$SESS_DBH = ""; 
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime"); 
……//定制函数 
session_set_save_handler( "sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc"); 
?> 
  定制使用dbm文件时的接口 : 
<? 
$SESS_DBM = ""; 
$SESS_LIFE = get_cfg_var("session.gc_maxlifetime"); 
……//定制函数 
session_set_save_handler("sess_open", "sess_close", "sess_read", "sess_write", "sess_destroy", "sess_gc"); 
?> 
  session定制的测试代码: 
<?php 
…… 
if ($handler == "dbm") include("session_dbm.php");//使用何种接口 
elseif ($handler == "mysql") include("session_mysql.php"); 
else …… 
session_start(); 
session_register("count");
......
?>
 How to use Session in authentication?
 Session can be used for user authentication:
Verify whether the user is legitimate:
  <?
  session_start();
  …//Verification process
  session_register("reguser");
   ?>
Check whether the user is logged in on another page
  <?
  session_start();
  if(isset($reguser)&&$reguser!=""){//If you are already logged in
  echo "Dear user, welcome";
  }else{//If you are not logged in
   echo "Please register first!";
   }
                                                    Generation your by in combinating sessions Shipping operation?
 Question: When I was writing a purchase, sales and inventory system for my unit, I found that it was necessary to allow multiple users to enter a php application at the same time. The originally designed static unique session ID caused data confusion. In this way, dynamically generating a unique session ID becomes a top priority.
 The solution is simple: I used the php file name + timestamp as the unique session ID, so that each session in my program is in its place and there is no longer confusion.
I will publish my source code below so that friends who have the same problem can find a solution.
//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 to pass variables for the unique sessionname between pages. If you also use this name, you must make a small change in 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 in cookie mode, because multiple sessions will definitely overwrite the original cookie file. You can save it using hidden form fields. Then there will be no problem.





For more detailed explanations on how to use sessions in PHP, please pay attention to the PHP Chinese website for related articles on page 2/2!

Statement:
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