0
0
PHPprogramming~5 mins

Cookie expiration and security in PHP

Choose your learning style9 modes available
Introduction

Cookies store small data on a user's browser. Setting expiration controls how long the cookie lasts. Security settings keep cookies safe from hackers.

Remembering a user login for a few days without asking again.
Keeping a shopping cart active for a limited time.
Protecting sensitive cookies from being stolen by attackers.
Making sure cookies are only sent over secure connections.
Setting cookies that expire when the browser closes.
Syntax
PHP
setcookie(name, value, expire, path, domain, secure, httponly);

expire is a timestamp (seconds since 1970) when the cookie expires.

secure means cookie is sent only over HTTPS.

httponly means cookie cannot be accessed by JavaScript.

Examples
Cookie named 'user' expires in 1 hour (3600 seconds).
PHP
setcookie("user", "Alice", time() + 3600);
Session cookie for 'example.com' domain, sent only over HTTPS, not accessible by JavaScript, expires when browser closes.
PHP
setcookie("session", "abc123", 0, "/", "example.com", true, true);
Cookie 'cart' expires in 1 day, valid only in '/shop' path.
PHP
setcookie("cart", "5", time() + 86400, "/shop");
Sample Program

This program sets a cookie named 'username' that lasts 2 hours, is sent only over HTTPS, and is not accessible by JavaScript. It then checks if the cookie exists and greets the user accordingly.

PHP
<?php
// Set a cookie that expires in 2 hours, secure and httponly
setcookie("username", "Bob", time() + 7200, "/", "", true, true);

// Check if cookie is set
if (isset($_COOKIE["username"])) {
    echo "Welcome back, " . $_COOKIE["username"] . "!";
} else {
    echo "Hello, new visitor!";
}
?>
OutputSuccess
Important Notes

Cookies must be set before any HTML output in PHP.

Use time() + seconds to set expiration in the future.

Setting secure to true requires HTTPS connection.

Summary

Cookie expiration controls how long the cookie stays on the browser.

Security flags like secure and httponly protect cookies from theft and misuse.

Always set cookies before sending any output in PHP.