Cookie与Session
Cookie
Cookie功能
创建cookie
<?PHP
setcookie("TMCookie" ,'www.baidu.com');
setcookie("TMCookie" ,'www.baidu.com' ,time()+60);
?>
读取Cookie
<?PHP
if(!isset($_COOKIE["visittime"])){
setcookie("visittime" ,date("y-m-d H:i:s"));
echo "Huan Ying Di Yi Ci Fang Wen Wang Zhan!<br>";
}else{
setcookie("visittime" ,date("y-m-d H:i:s") ,time()+60);
echo "Shang Ci Fang Wen Shi Jian:".$_COOKIE["visittime"];
echo "<br>";
}
echo "Ben Ci Fang Wen Shi Jian:".date("y-m-d H:i:s");
?>
删除cookie
<?PHP
setcookie("visittime" ,"" ,time()-1);
?
Session
关于Session
创建Session
<?PHP
session_start();
?>
注册Session
<?PHP
session_start();
$_SESSION["admin"] = null;
?>
使用Session
<?PHP
if(!empty($_SESSION["admin"])) {
$myvalue = $_SESSION["admin"];
echo $myvalue;
}
?>
删除会话
<?PHP
//session_start();
//删除单个会话
unset($_SESSION["admin"]);
//删除多个会话
$_SESSION = array();
//结束当前会话
session_destroy();
?>
Session失效时间
<?PHP
$time = 1*60;
session_set_cookie_params($time);
session_start();
$_SESSION["USERNAME"]='CC';
?>
Tip:session_set_cookie_params 函数不是所有浏览器的支持。
通过cookie设置sessionid来控制session时间
<?PHP
session_start();
$time = 1 * 60;
setcookie(session_name() ,session_id() ,time()+$time,"/");
$_SESSION['user'] = 'cc';
?>
如果客户端禁止使用Cookie的话Session页面间传递会失败,如下方法解决这个问题:
第三种方式的代码如下:
发送页面:
<?PHP
session_start();
$_SESSION['user'] = 'cc';
$urlt='301.php?'.session_name().'='.session_id();
echo "<a href=$urlt>session_id_go</a>";
?>
接受页面
<?php
$sess_name=session_name();
$sess_id = $_GET[$sess_name];
session_id($sess_id);
session_start();
echo $_SESSION['user'];
?>
Session临时文件:
<?PHP
$paths='./tmp/';
session_save_path($paths);
session_start();
$_SESSION['user'] = 'cc';
$_SESSION['www'] = '12345';
?>
Session本地客户端缓存
Session数据库存储
...