lain
answered Apr 27 '23 00:00
To get the value of a cookie in PHP, you can use the $_COOKIE superglobal variable. Here's an example:
// Set a cookie
setcookie("username", "john_doe", time()+3600);
// Get the value of the cookie
$username = $_COOKIE['username'];
// Output the value of the cookie
echo $username; // Output: john_doe
In this example, we set a cookie called username with the value john_doe and an expiration time of 1 hour from the current time. We then retrieve the value of the cookie by accessing the $_COOKIE superglobal variable with the name of the cookie as the key. Finally, we output the value of the cookie using the echo statement.
Note that if the cookie is not set or has expired, the $_COOKIE superglobal variable will not contain the cookie and attempting to access it may result in an error. You can use the isset() function to check whether a cookie is set before attempting to access its value:
if (isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
echo $username;
} else {
echo "Cookie not set";
}
In this example, we use the isset() function to check whether the username cookie is set. If it is, we retrieve its value and output it. If it is not set, we output a message indicating that the cookie is not set.