Cookie là gì?
Cookie thường được sử dụng để xác định người dùng. Cookie là một tệp tin nhỏ mà máy chủ được nhúng vào máy tính của người dùng. Mỗi khi cùng một máy tính yêu cầu một trang với trình duyệt, nó cũng sẽ gửi cookie. Với PHP, bạn có thể tạo và lấy các giá trị cookie.
Tạo cookie với php
Cú pháp:
setcookie(name, value, expire, path, domain, secure, httponly);
Ví dụ tạo 1 cookie:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the value of the cookie.</p>
</body>
</html>
Kết quả :
Cookie named 'user' is not set!
Note: You might have to reload the page to see the value of the cookie.
Thay đổi cookie
Vi dụ:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
<p><strong>Note:</strong> You might have to reload the page to see the new value of the cookie.</p>
</body>
</html>
Kết quả:
Cookie 'user' is set!
Value is: John Doe
Note: You might have to reload the page to see the new value of the cookie.
Xóa cookie
Ví dụ:
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Kết quả:
Cookie 'user' is deleted.
Check cookie có tồn tại
Ví dụ:
<!DOCTYPE html>
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Kết quả:
Cookies are enabled.