php自定文件夹|php自定文件保存session实现方法

更新时间:2016-11-01    来源:脚本编码    手机版     字体:

【www.bbyears.com--脚本编码】

//session.inc.php教程文件:定义session的文件存储,session解决方案,就是要提供在php脚本中定义全局变量的方法,使得这个全局变量在同一个session中对于所有的php脚本都有效。上面我们提到了,session不是一个简单的时间概念,一个session中还包括了特定的用户和服务器。因此更详细地讲,在一个session定义的全局变量的作用范围,是指这个session所对应的用户所访问的所有php。   例如a用户通过session定义了一个全局变量$user=“wind”中,而b用户通过session定义的全局变量$user=“jane”。那么在a用户所访问的php脚本中,$user的值就是wind。php如何创建session
  开始介绍如何创建 session。非常简单,真的。   启动 session 会话,并创建一个 $admin 变量:   // 启动 session   session_start();   // 声明一个名为 admin 的变量,并赋空值。   $_session["admin"] = null;   ?>   如果你使用了 seesion,或者该 php 文件要调用 session 变量,那么就必须在调用 session 之前启动它,使用 session_start() 函数。其它都不需要你设置了,php 自动完成 session 文件的创建。   执行完这个程序后,我们可以到系统临时文件夹找到这个 session 文件,一般文件名形如:sess_4c83638b3b0dbf65583181c2f89168ec,后面是 32 位编码后的随机字符串。用编辑器打开它,看一下它的内容:   admin|n;


//定义一个超全局数组

$_session = array();

//定义文件句柄

$fp = null;


//用户自定义的开启session函数

function session_file_start() {

 

//1. 首先判断浏览器有没有发送cookie值

if (isset($_cookie["fileid"])) {

 

//2. 接收cookie值

$filename = $_cookie["fileid"];


//3. 打开文件,用于读写

if (file_exists($filename)) {

$globals["fp"] = fopen($filename, "r+");

} else {

$globals["fp"] = fopen($filename, "w+");

}


} else {

 

//2. 设置一个文件,并把该文件名放到cookie中

$filename = date("ymdhis");

setcookie("fileid", $filename, time()+60*60*24);


//3. 打开文件,用于读写

$globals["fp"] = fopen($filename, "w+");


} //end of if-else


//4. 把文件中的数据存储到超全局数组$_session中

while (!feof($globals["fp"])) {

//读取文件中的一行

$buffer = fgets($globals["fp"]);

//处理所读取的这一行

$tmparr = explode("=", trim($buffer, "rn"));


//添加到session数组中

if (count($tmparr) == 2) {

$globals["_session"][$tmparr[0]] = $tmparr[1];

}

} //end of while


} //end of session_file_start()


//注册会话变量的函数

function session_file_register($key, $val) {

 

//设定session变量

$globals["_session"][$key] = $val;


//把该变量放到文件中

fseek($globals["fp"], 0, seek_end);

fwrite($globals["fp"], "$key=$valrn");


} //end of session_file_register()


//结束会话变量

function session_file_destroy() {

 

//1. 关闭文件指针

fclose($globals["fp"]);

$fp = null;


//2. 设置session数组为空

$globals["_session"] = array();


} //end of session_file_destroy()

//测试代码文件:1.php

//确定编码格式

header("content-type: text/html; charset=utf-8");


include("session-file.php");


//测试函数:

//开启会话

session_file_start();


//注册会话变量

$key = "username";

$val = "lsl";

session_file_register($key, $val);


session_file_register("username", "lisa");


//打印session数组

echo $_session["username"];

 


?>

下一页


//测试文件:2.php

//确定编码格式

header("content-type: text/html; charset=utf-8");


include("session-file.php");


//测试函数:

//开启会话

session_file_start();


echo $_session["username"];


?>

本文来源:http://www.bbyears.com/aspjiaocheng/27961.html

猜你感兴趣