Set PHP Cookie for setting username and one hour expiration
1. Set "username" Cookie with Expiry
Write a PHP script to set a cookie named "username" with the value "Gulnara Serik" and an expiration time of one hour.
Sample Solution:
PHP Code :
<?php
$cookieName = "username";
$cookieValue = "Gulnara Serik";
$expirationTime = time() + 3600; // current time + 1 hour
setcookie($cookieName, $cookieValue, $expirationTime);
echo "Cookie named 'username' has been set with the value 'Gulnara Serik'.";
?>
Sample Output:
Cookie named 'username' has been set with the value 'Gulnara Serik'.
Explanation:
In the above exercise -
We have three variables:
- $cookieName: The cookie name, set to "username".
- $cookieValue: The cookie value, set to "Gulnara Serik".
- $expirationTime: The cookie expiration time, calculated as the current time (time()) plus 1 hour (3600 seconds).
We then use the setcookie() function to set the cookie with the specified name, value, and expiration time.
After setting the cookie, we display a message indicating that the cookie has been set.
When a user visits this script, a cookie named "username" will be set in their browser with the value "Gulnara Serik" and an expiration time of one hour.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to set a cookie with the name "username", a dynamic user value, and an expiration time of 3600 seconds from now.
- Write a PHP function to set a cookie with the name "username" and include additional parameters like path, domain, and secure flag.
- Write a PHP script to set a cookie named "username" and then display its value on the next page load to verify persistence.
- Write a PHP program to set a cookie with "username" and log the cookie details (name, value, expiration) to a file for auditing.
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP Cookies and Sessions Exercises Home.
Next: Retrieve and display PHP cookie value for a given user.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.