Cookie
设置cookie:
//expire:cookie存在时间
//domain:为一个子域名设置cookie,默认是域下所有子域
set cookie(name, value, expire, path, domain);
实例:
<?php
$expire=time()+60*60*24*30;
setcookie("user", "runoob", $expire);
?>
<html>
函数的调用条件:必须在任何输出之前设置
取回cookie的值:
<?php
echo $_COOKIE["user"];
print_r($_COOKIE);
?>
可以用isset()函数来检测某个名称的cookie数据是否已经设置:
if (isset($_COOKIE["user"])){
echo "已经设置cookie";
}
Cookie数据的删除:
用set cookie来设置某个名称的cookie为空,并且有效时间为过去的时间,来达到删除的目的。
<?php
setcookie("user", "", time()-3600);
?>
Session
开始Session会话,必须在任何输出内容之前
<?php session_start(); ?>
<html>
<body>
</body>
</html>
存取Session变量
<?
phpsession_start();
// 存储 session 数据
$_SESSION['views']=1;
?>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<?php
// 检索 session 数据
echo " ". $_SESSION['views'];
?>
</div>
</body>
</html>
Session变量的销毁
unset()函数用于释放指定的session变量:
<?php
session_start();
if(isset($_SESSION['views'])) {
unset($_SESSION['views']);
}
?>
session_destroy()函数彻底销毁session,并且重置session
实例应用
<html>
<div>
<?php
$isLogin = false;
$userinfo = array(
"xuqian" => "123123",
);
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$username = $_POST['username'];
$password = $_POST['password'];
if(!(empty($username) || empty($password))){
echo "进入---> <br/>";
if($password == $userinfo[$username]){
$expire = time() + 60*5;
setcookie("user","xuqian",$expire);
$isLogin = true;
echo "post----";
}
}else {
$login = false;
}
}
if(isset($_COOKIE['user'])){
$isLogin = true;
echo "cookie --------";
}
?>
</div>
<head>
<meta charset = 'utf-8'/>
<title>测试表单</title>
</head>
<body>
<div>
<?php
if($isLogin){
echo "Wellcome !!!!!!!!";
}
else{
echo "Please Login !!!!";
}
?>
</div>
<form action="#" method="POST">
用户名:<input type="test" name="username"><br/>
密 码:<input type="password" name="password"><br/>
<input type="submit" name="submit" value="提交"/>
</form>
<div>
<?php
echo "用户名: "; echo $_POST['username'];echo "<br/>";
echo "密码: "; echo $_POST['password'];
if (!empty($_POST['submit'])){
if (empty($_POST['password'])){
echo "NULL";
}
}
?>
</div>
</body>
</html>
网友评论