What are some best practices for setting and deleting specific values in $_COOKIE in PHP?
When setting specific values in $_COOKIE in PHP, it is important to sanitize user input to prevent security vulnerabilities such as cross-site scripting attacks. It is also recommended to set an expiration time for the cookie to ensure it is not stored indefinitely on the user's browser. When deleting specific values from $_COOKIE, make sure to unset the specific key from the $_COOKIE array.
// Setting a specific value in $_COOKIE
$cookie_name = "user";
$cookie_value = "John Doe";
$expiry = time() + (86400 * 30); // 30 days
setcookie($cookie_name, $cookie_value, $expiry, '/');
// Deleting a specific value from $_COOKIE
if (isset($_COOKIE['user'])) {
unset($_COOKIE['user']);
setcookie('user', '', time() - 3600, '/');
}
Keywords
Related Questions
- What steps should be taken to ensure consistent character encoding across PHP scripts, databases, and HTML for proper display of special characters like umlauts?
- What is the potential security risk of passing serialized arrays via GET in PHP?
- What are the advantages and disadvantages of using database transactions in PHP to manage seat reservations?