What is the best practice for setting and checking cookies in PHP?
When setting and checking cookies in PHP, it is important to properly sanitize and validate user input to prevent security vulnerabilities such as cross-site scripting attacks. It is also recommended to set the cookie parameters securely, including setting the 'secure' flag for HTTPS connections and 'httponly' flag to prevent access via JavaScript.
// Set a cookie with secure and httponly flags
setcookie('user', 'John Doe', time() + 3600, '/', '', true, true);
// Check if the cookie is set
if(isset($_COOKIE['user'])) {
echo 'Welcome back, ' . $_COOKIE['user'];
} else {
echo 'Welcome, guest';
}
Keywords
Related Questions
- In what scenarios would it be more beneficial to create a custom HTML to PDF parser instead of using existing PHP libraries like html2pdf or fpdi?
- What are the best practices for organizing and accessing PHP files in a local development environment like XAMPP?
- What are the best practices for implementing a countdown in PHP that displays "starting soon" when it expires?