Home > Article > Backend Development > php基础教程——3cookie跟session
php基础教程——3cookie和session
一、cookie
1.创建cookie,注:必须在发送其他任何信心之前从服务器发送到客户端,否则导致错误。
使用函数发送cookie: setcookie(name, value);
2.读取cookie
eg:setcookie('user', 'trout');
$COOKIE['user'];
3.添加参数
set(name, value, expiration, path, domain, sesure, httponly);
参数简介:
name键, value值,
expiration存在时间,
path和 domain限制在特定文件夹或域中才存在,
sesure值1表必须使用安全连接,反之值0表不必要,
httponly限制对cookie的访问,比如禁止Javascript对cookie的访问。
4.删除cookie
使用通首次设置cookie时相同的参数,不设置值。
eg:setcookie('user', 'larry');
删除:setcookie('user', '');
编码测试:ws.php:
<?php if (isset($_POST['submitted'])){ setcookie('font-size', $_POST['font_size'], time() + 1000000000, '/', '', 0); setcookie('font-color', $_POST['font_color'], time() + 1000000000, '/', '', 0); $msg = '<p>setted!';}?> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title><base> <?phpif (isset($msg)){ print $msg;}?><p>Choose your preferences:</p>
<div><p>This is the foot of the document</p></div>
1.session与cookie区别:
1>session将信息保存于服务器,cookie保存于客户端
2>session保存信息量更大
3>session更安全
2.创建session,注:必须在向web发信息之前调用
1>调用函数:session_start();
2>通过数组$_SESSION进行数值记录:$_SESSION[' email '];
3.访问session:
$_SESSION[' email '];
4.删除session:session数据存在两个地方,故从两个地方删除:
1>session_start()
2>unset($_SESSION);
3>session_destory(); //删除服务器上的
编码测试:ws.php:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>test</title><base> <?phpdefine ('TITLE', 'Login');if (isset($_POST['submitted'])) { if ((!empty($_POST['name'])) && (!empty($_POST['password']))){ if ((strtolower($_POST['name']) == 'yf') && ($_POST['password'] == '123456')){// name and password are correct. session_start(); $SESSION['name'] = $_POST['name']; $SESSION['time'] = time(); print '<h1>The session content:' .$SESSION['name']."\n".$SESSION['time'].''; unset($_SESSION); session_destroy(); print 'destroy()!'; } else { print '<p> name or password is worry!</p>'; } } else { print '<p> make sure you enter both name and password!</p>'; }}else { print ''; }?><div><p>This is the foot of the document</p></div>
测试裁图:
结果: