Bài giảng Lập trình Web - Bài 4.2: Cookie
Cookie
COOKIE
Dùng để lưu thông tin của người dùng.
Cookie được lưu ở máy client, browser
quản lý
Mỗi biến cookie có 1 thời gian quá hạn.
Vượt qua thời điểm đó, browser sẽ xóa
biến cookie
Mỗi lần thực hiện request 1 trang, browser
sẽ gửi lại các biến cookie chưa hết hạn
Được đặt trước thẻ <html>
2
COOKIE
Tạo cookie
. Cú pháp
setcookie(“tên”, giá-trị [, thời
điểm quá hạn])
Sử dụng cookie
. $_COOKIE là dãy biến toàn cục sẵn có trong
php
. Cú pháp sử dụng biến cookie
$_COOKIE[“TenBien”]
3
COOKIE
setcookie.php
<?php
$value = "something from somewhere";
setcookie("TestCookie", $value, time() +
3600); /* hết hạn trong 1 giờ */
?>
viewcookie.php
<?php
if(isset($_COOKIE["TestCookie"]==true))
echo $_COOKIE["TestCookie"];
?>
4
COOKIE
<?php
setcookie("cookie[three]", "cookiethree");
setcookie("cookie[two]", "cookietwo");
setcookie("cookie[one]", "cookieone");
// after the page reloads, print them out
if (isset($_COOKIE['cookie'])){
foreach ($_COOKIE['cookie'] as $name => $value){
$name = htmlspecialchars($name);
$value = htmlspecialchars($value);
echo "$name : $value <br />\n";
}
}
?>
5
COOKIE – ví dụ
Form đăng nhập
<form name="frmdangnhap" method="post"
action="xuly.php">
Tên <br/>
<input type="text" name="txtten"/> <br/>
Mật khẩu <br/>
<input type="password" name="txtmatkhau" /><br/>
<input type="checkbox" name="chknho" />
Nhớ thông tin này <br/>
<input type="submit" name="btngui" value="Gửi"/>
</form>
6
COOKIE – ví dụ
xuly.php
<?php
if(isset($_POST["chknho"]) == true){
setcookie("ten",$_POST["txtten"],time()+3600)
;
setcookie("matkhau",$_POST["txtmatkhau"],time
()+3600);
}
else{
setcookie("ten",$_POST["txtten"],-1);
setcookie("matkhau",$_POST["txtmatkhau"],-1);
}
?>
7
Session
SESSION
Session là đối tượng trên server, chứa
thông tin của từng user
Mỗi user có vùng session riêng biệt
$_SESSION là 1 dãy toàn cục có sẵn
trong php.
9
SESSION
Tạo session
. $_SESSION["sessionName"] = value;
. $_SESSION["sessionName"][ ]=
array(…);
Đọc giá trị session
. if (isset($_SESSION[sessionName"])
echo $_SESSION["sessionName"];
Xóa bỏ session
. unset($_SESSION["sessionName"]);
. session_destroy();
10
SESSION
VD
<?php
session_start();
$_SESSION["login"]=1;
$_SESSION["name"]="abc";
header("Location: index.php");
?>
11
Ứng dụng Session
Làm thế nào để ngăn không cho người
dùng truy cập vào các trang web nếu chưa
đăng nhập?
Ý tưởng: dùng các biến Session để lưu
trạng thái đăng nhập của người dùng
. $_SESSION[“Login”] = 0/1: lưu trạng thái
đăng nhập
. $_SESSION[ “Username”]: lưu tên đăng nhập
. $_SESSION[ “Authentication”]: lưu loại quyền
đăng nhập
. …
12
Ứng dụng Session
Tạo trang login.htm yêu cầu người dùng đăng nhập
Tạo trang validateuser.php xử lí thông tin đăng nhập từ
trang login
. Kết nối với CSDL, kiểm tra xem thông tin đăng nhập có
đúng hay không
. Nếu không đúng thì cho chuyển hướng đến trang
login.htm
. Nếu đúng thì dùng một biến Session để lưu trạng thái
login thành công lại.
• Ví dụ $_SESSION["IsLogin“] = 1;
Tạo trang logout.php là trang xử lý khi người dùng logout
. Reset trạng thái login là chưa đăng nhập
• Ví dụ unset($_SESSION[“IsLogin”]);
13
Tập tin, thư mục
Quản lý file & thư mục
Hàm thao tác trên file
. res fopen(string $filename, string
$mode)
. bool fclose(res $handle)
. int fpassthru (res $handle)
gửi toàn bộ nội dung file đang mở cho browser
(binary)
. int readfile (string $filename)
gửi toàn bộ nội dung file đang mở cho browser (text)
. string fread(res $handle, int $length)
đọc một khối dữ liệu dài tối đa length (binary)
. int fwrite(res $handle, string $str [,
int $length])
ghi nội dung của chuỗi ra file
15
Quản lý file & thư mục
Hàm thao tác trên thư mục
. bool chdir ( string $directory ):
Chuyển thư mục hiện hành
. string getcwd (): Trả về thư mục hiện hành
. resource opendir (string $path): Mở
một thư mục trước khi đọc nội dung
. void closedir (res $dir_handle): Đóng
thư mục đã mở trước đó
. bool mkdir ( string $pathname): Tạo thư
mục
. bool rmdir ( string $dirname): Xóa thư
mục
16
VD hàm xóa thư mục
<?php
function removeDirectory($dir){
$s = DIRECTORY_SEPARATOR;
$dir = opendir($dir);
while(($file=readdir($dir))!==false){
if (is_file($dir . $s . $file)) {
unlink($dir . $s .$file);
} else if(is_dir($dir . $s .$file)
&&($file != ".")&&($file != "..")) {
removeDirectory($dir .$s. $file);
} }
closedir($dir); rmdir($dir);
printf("Directory %s removed", $dir);
}
?>
17
File Upload
<html>
<head><title> Form for Uploading a File </title>
</head>
<body>
<h2> A simple form for uploading a file </h2>
<form action="upload.php" method="post
enctype="multipart/form-data">
Enter file name: <input type="file"
name="userfile"><br>
<input type="submit"><br>
</form>
</body> </html>
18
File Upload
userfile: tên của input trong form upload
$_FILES['userfile']['name']
. Tên file đã được upload.
$_FILES['userfile']['type']
. Kiểu của file được upload nếu trình duyệt có
thông tin này. Ví dụ "image/gif“
$_FILES['userfile']['size']
. Kích thước của file đã upload tính bằng byte.
$_FILES['userfile']['tmp_name']
. Vị trí file được lưu trữ tạm trên server.
$_FILES['userfile']['error']
. Mã lỗi của việc upload (0 == no error)
19
File Upload
<?php
$target = "demo/";
$target = $target . basename(
$_FILES['uploaded']['name']) ;
$ok=1;
if(move_uploaded_file($_FILES['uploaded']
['tmp_name'], $target))
{
echo "The file ". basename(
$_FILES['uploadedfile']['name']). "
has been uploaded";
}
else { echo "Sorry, there was a problem
uploading your file.";
}
?>
20
Tải về để xem bản đầy đủ
Bạn đang xem 20 trang mẫu của tài liệu "Bài giảng Lập trình Web - Bài 4.2: Cookie", để tải tài liệu gốc về máy hãy click vào nút Download ở trên
File đính kèm:
- bai_giang_lap_trinh_web_bai_4_2_cookie.pdf