Retrieve and display PHP cookie value for a given user
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics