Retrieve and display PHP cookie value for a given user
2. Retrieve "username" Cookie
Write a PHP script to retrieve and display the value of the cookie named "username".
Sample Solution:
PHP Code :
<?php
$cookieName = "username";
if (isset($_COOKIE[$cookieName])) {
$cookieValue = $_COOKIE[$cookieName];
echo "Value of cookie 'username': " . $cookieValue;
} else {
echo "Cookie 'username' not found.";
}
?>
Sample Output:
Value of cookie 'username': Gulnara Serik.
Explanation:
In the above exercise -
- First we define the variable $cookieName with the name of the cookie we want to retrieve, which is "username".
- Next, we use the isset() function to check if the cookie with the specified name exists in the $_COOKIE superglobal array. If it exists, we retrieve its value using $_COOKIE[$cookieName] and store it in the variable $cookieValue.
- We then display the cookie value by echoing the message "Value of cookie 'username': " concatenated with $cookieValue.
- If the cookie does not exist, we display the message "Cookie 'username' not found."
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to safely retrieve the cookie "username" and output its value, handling cases where it may not be set.
- Write a PHP function to check if the "username" cookie exists and then display a custom greeting message.
- Write a PHP program that retrieves the "username" cookie and prints its value along with the current timestamp.
- Write a PHP script to retrieve the "username" cookie and compare its value with a predefined string for validation.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: Set PHP Cookie for setting username and one hour expiration.
Next: Delete a given PHP cookie.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.