Cookies in php with syntax and examples
ookies are small text files stored on a client's device, allowing you to track user data and preferences across multiple requests.
Setting Cookies:
Syntax: setcookie(name, value, expire, path, domain, secure, httponly)
Example:
setcookie('username', 'JohnDoe', time() + 86400, '/', '', '', true);
Retrieving Cookies:
Syntax: $_COOKIE['name']
Example:
echo $_COOKIE['username']; // outputs "JohnDoe"
Cookie Parameters:
1. name: Cookie name
2. value: Cookie value
3. expire: Expiration time (Unix timestamp)
4. path: Cookie path
5. domain: Cookie domain
6. secure: Secure cookie (HTTPS only)
7. httponly: HTTP-only cookie (JavaScript inaccessible)
Cookie Examples:
1. Setting a cookie with a specific expiration time:
setcookie('username', 'JohnDoe', time() + 3600); // expires in 1 hour
1. Setting a secure cookie:
setcookie('username', 'JohnDoe', time() + 86400, '/', '', '', true);
1. Deleting a cookie:
setcookie('username', '', time() - 3600); // deletes the cookie
Cookie Security:
1. Use secure cookies (HTTPS only)
2. Use HTTP-only cookies (JavaScript inaccessible)
3. Validate and sanitize cookie data
4. Use a secure cookie name and value
Best Practices:
1. Use cookies for non-sensitive data
2. Set cookies with a specific expiration time
3. Use secure and HTTP-only cookies
4. Validate and sanitize cookie data
5. Test cookie functionality thoroughly
By understanding cookies in PHP, you can create personalized experiences and track user data across multiple requests.