PHP學習練手(十三)
COOKIE
特性: cookie將資料儲存在使用者的瀏覽器中。
流程:
程式碼:
1.login_page.inc.php
<?php #Script 12.1 - login.inc.php
$page_tile = 'Login';
include('../include/header.html');
if(isset($errors) && !empty($errors))
{
echo '<h1>Error!</h1>
<p class="error">The following error(s) occurred:<br />' ;
foreach ($errors as $msg) {
echo "- $msg<br />\n";
}
echo '</p><p>Please try again.</p>';
}
?>
<h1>Login</h1>
<form action="login1.php" method="post">
<p>Email Address: <input type="text" name="email" size="20" maxlength="60" /></p>
<p>Password: <input type="password" name="pass" size="20" maxlength="20" /></p>
<p><input type="submit" name="submit" value="Login" /></p>
</form>
<?php include('../include/footer.html'); ?>
注:
1、該頁面使用.inc.php副檔名,指示它是一個可包含的檔案並且它包含PHP程式碼
執行:
2.login_function.inc.php
<?php # Script 12.2 - login_functions.inc.php
//絕對url路徑
//函式實現頁面跳轉到index1.php功能
function redirect_user($page = 'index1.php')
{
$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF']);
$url = trim($url, '/\\');
$url .= '/'.$page;
header("Location: $url"); //頁面跳轉
exit();
}
function check_login($mysqli, $email='', $pass='')
{
//檢查email Address
if (empty($email))
{
$errors[] = 'You forgot to enter your email';
}else{
$e = mysqli_real_escape_string($mysqli, trim($email));
}
//檢查pass
if (empty($pass))
{
$errors[] = 'You forgot to enter your email';
}else{
$p = mysqli_real_escape_string($mysqli, trim($pass));
}
if(empty($errors))
{
$sql = "SELECT user_id, first_name FROM users WHERE email = '$e' AND pass = SHA1('$p')";
$res = @mysqli_query($mysqli, $sql);
if(mysqli_num_rows($res) == 1)
{
$rows = mysqli_fetch_array($res, MYSQLI_ASSOC);
return array(true, $rows);
}else{
$errors[] = 'The email address and password entered do not match those on file';
}
}
return array(false, $errors);
}
?>
注:
1、$_SERVER[‘HTTP_HOST’]:Contents of the Host: header from the current request, if there is one.根據客戶端的HTTP請求輸出資訊
2、$_SERVER[‘PHP_SELF’] :表示當前 php 檔案相對於網站根目錄的位置地址
3、dirname() :函式返回路徑中的目錄部分
4、rtrim() :函式移除字串右側的空白字元或其他預定義字元
3.login.php
<?php # Script 12.3 - login.php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
require('../include/login_function.inc.php');
require_once ('../mysqli_connect.php');
list($check, $data) = check_login($mysqli, $_POST['email'], $_POST['pass']);
if($check)
{
setcookie('user_id', $data['user_id']);
setcookie('first_name', $data['first_name']);
redirect_user('loggedin.php');
}else{
$errors = $data;
}
mysqli_close($mysqli);
}
include('../include/login_page.inc.php');
?>
注:
1、cookie必須在其他任何資訊之前把它們從伺服器傳送給客戶。萬一伺服器試圖在web瀏覽器已經接收到HTML(甚至是無關緊要的空白)之後傳送cookie,就會導致一條錯誤訊息,並且不會發送cookie。
2、通過setcookie()函式傳送cookie
3、cookie被限制為總共包含大約4KB的資料,每個Web瀏覽器可以記住來自任何一個站點的有限數量的cookie。對目前的大多數瀏覽器,這個限制是50個
執行:
4.loggedin.php
<?php # Script 12.4 - loggedin.php
if(!isset($_COOKIE['user_id']))
{
require('../include/login_function.inc.php');
redirect_user(); //登入不成功返回到首頁index1.php
}
//print_r($_COOKIE);
$page_title = 'Logged In';
include('../include/header.html');
echo "<h1>Logged In</h1>
<p>You are now logged in, {$_COOKIE['first_name']}</p>
<p><a href=\"logout.php\">Logout</a></p>";
include('../include/footer.html');
?>
注:
1、訪問cookie:$_COOKIE
執行:
5.login1.php
<?php # Script 12.3 - login.php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
require('../include/login_function.inc.php');
require_once ('../mysqli_connect.php');
list($check, $data) = check_login($mysqli, $_POST['email'], $_POST['pass']);
if($check)
{
setcookie('user_id', $data['user_id'], time()+30, '/', '', 0, 0);
setcookie('first_name', $data['first_name'],time()+30, '/', '', 0, 0);
print_r($_COOKIE);
redirect_user('loggedin.php');
}else{
$errors = $data;
}
mysqli_close($mysqli);
}
include('../include/login_page.inc.php');
?>
注:
1、setcookie('user_id', $data['user_id'], time()+30, '/', '', 0, 0);
設定cookie的到期時間
6.logout.php
<?php # Script 12.6 - logout.php
if(!isset($_COOKIE['user_id']))
{
require('../include/login_function.inc.php');
redirect_user();
}else{
setcookie('user_id', '', time()-3600, '/', '', 0, 0);
setcookie('first_name', '', time()-3600, '/', '', 0, 0);
}
$page_title = 'Loggout Out!';
include('../include/header.html');
echo "<h1>Logged Out!</h1>
<p>You are now logged out, {$_COOKIE['first_name']}!</p>";
include('../include/footer.html');
?>
注:
1、刪除cookie:
假設cookie設定為 setcookie(‘user’, ‘Lee’);
刪除cookie方式一:setcookie(‘user’);
刪除cookie方式二:setcookie(‘user’,”, time()-3600);//把到期日期設定成過去的某個日期
2、剛開始搞不懂:
test.php
<?php
setcookie('test','TEST'); //建立cookie
print_r($_COOKIE);
?>
第一次在瀏覽器中重新整理時,為什麼輸出的是空矩陣沒有TEST值。然後執行:
test1.php
<?php
setcookie('test','',time()-3600); //清除建立的cookie
print_r($_COOKIE);
?>
已經把cookie登出了,為什麼print_r還能輸出值。
後來一番百度,終於找到詳細的解釋了:
php第一次無法獲取cookie問題處理
現自己總結一下,加深印象O(∩_∩)O哈!
1)當在瀏覽器端第一次訪問test.php指令碼時,可以看到瀏覽器與服務端兩者傳送的訊息頭如下:
此時伺服器響應setcookie命令,但是因為cookie是設定在客戶端的,setcookie函式自己並不能設定cookie,它只能通過頭資訊的方式告訴瀏覽器說:兄弟,我要設定一個cookie,鍵為a,值為value,你在你那裡幫我設定一下。
2)執行print_r($_COOKIE); 因為客戶端訪問伺服器的時候,這個cookie壓根就不存在,而前面第一步設定cookie的頭資訊,也還沒有返回給客戶端(php要從上到下把語句執行完才會返回給客戶端),所以此時顯示為空矩陣
3)再次重新整理test.php。資訊頭如下:
此時返回
4)第一次執行test1.php。發現test的cookie記錄表不在了,說明成功刪除了cookie
但是$_COOKIE中仍有值:
同理,這是因為print_r(
執行:
7.修改後的header.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $page_title; ?></title>
<link rel="stylesheet" href="../include/style.css" type="text/css" media = "screen">
</head>
<body>
<div id="header">
<h1>Your Website</h1>
<h2>catchy slogan...</h2>
</div>
<div id="navigation">
<ul>
<li><a href="index1.php">Home Page</a></li>
<li><a href="register.php">Register</a></li>
<li><a href="view_users5.php">View Users</a></li>
<li><a href="password.php">Change Password</a></li>
<li><?php
if((isset($_COOKIE['user_id'])) && (basename($_SERVER['PHP_SELF']) != 'logout.php'))
{
echo '<a href = "logout.php">Logout</a>';
}else{
echo '<a href="login1.php">Login</a>';
}
?></li>
</ul>
</div>
<div id="content"><!-- Start of the page-specific content-->
<!-- Script 9.1 - header.html -->
注:
1、basename() 函式返回路徑中的檔名部分。