In PHP, cookies are small pieces of data sent by the server to the client’s browser, which are then stored on the client’s computer. Cookies are commonly used for session management, user tracking, and personalization. Here’s an overview of PHP cookies along with examples:
You can set cookies using the setcookie()
function. Cookies must be set before any HTML output.
setcookie(name, value, expire, path, domain, secure, httponly);
setcookie("username", "John", time() + 3600, "/"); // Expires in 1 hour
Cookies are stored in the $_COOKIE
superglobal array and can be accessed like any other associative array.
echo $_COOKIE["username"]; // Output: John
To delete a cookie, you can set its expiration time to a past value.
setcookie("username", "", time() - 3600, "/"); // Expire immediately
if (isset($_COOKIE["username"])) {
$username = $_COOKIE["username"]; // Check if username exists in database and log in the user
} else {
// Prompt user to log in
}
Cookies are a fundamental aspect of web development, allowing you to store and retrieve data on the client’s machine. They are commonly used for session management, user authentication, and personalization in PHP applications.