Set PHP Cookie for setting username and one hour expiration
PHP Cookies and Sessions: Exercise-1 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/php-exercises/cookies-sessions/php-cookies-sessions-exercise-1.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics