- PHP Cookies
- PHP Password Encryption
- PHP Introduction
- PHP Variables and Arrays
- PHP Conditional Statements and Loops
- PHP GET and POST Variables
- PHP Connecting to MySQL
- PHP Creating Database and Table
- PHP MySQL Prepared Statements
- PHP Select operations
- PHP Session Variables
PHP Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax :
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example :
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
Check if Cookies are Enabled
The following example creates a small script that checks whether cookies are enabled. First, try to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
.
.
.
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
}
else {
echo "Cookies are disabled.";
}
?>