How can you set a cookie in PHP and retrieve its value later?
To set a cookie in PHP, you can use the `setcookie()` function with parameters for the cookie name, value, expiration time, and path. To retrieve the cookie value later, you can access it through the `$_COOKIE` superglobal array.
// Set a cookie with name 'user' and value 'John' that expires in 1 hour
setcookie('user', 'John', time() + 3600, '/');
// Retrieve the cookie value later
if(isset($_COOKIE['user'])){
$user = $_COOKIE['user'];
echo "Welcome back, $user!";
} else {
echo "Cookie not set.";
}
Keywords
Related Questions
- How can arrays be used to efficiently sort and display data from a database in PHP?
- How can one troubleshoot and fix errors related to incorrect calculation in PHP scripts?
- What are the best practices for continuously checking a variable in a MySQL table while a user is visiting a webpage using PHP?