Create A PHP Program Using Cookies
Create A PHP Program Using Cookies
Aim:
To create PHP program using cookies to display a personalized welcome message based on
whether the user is visiting for the first time or returning.
Algorithm:
1. Initialize cookie name as "username", cookie value as "Gulnara Serik", and expiry
time as current time + 1 hour.
2. Set the username Cookie using set cookie with the defined name, value, and expiry
time.
3. Check if username Cookie Exists and display its value if set; otherwise, indicate it’s
not set.
4. Retrieve and Display username Value again if it exists, or indicate it’s not set.
5. Delete the username Cookie by setting its expiry to a past time and checking if
deletion was successful.
6. Check for the visited Cookie and display a "Welcome back" message if set, or a
welcome message and set the cookie if not.
Program:
1.Write a PHP script to set a cookie named "username" with the value
"Gulnara Serik" and an expiration time of one hour.
<?php
$cookie_name = "username";
$cookie_value = "Gulnara Serik";
$expiry_time = time() + 3600;
setcookie($cookie_name, $cookie_value, $expiry_time, "/");
if (isset($_COOKIE[$cookie_name]))
{
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value: " . $_COOKIE[$cookie_name];
} else {
echo "Cookie '" . $cookie_name . "' is not set!";
}
?>
Output:
2.Write a PHP script to retrieve and display the value of the cookie named
"username".
<?php
if(isset($_COOKIE['username'])) {
$username = $_COOKIE['username'];
echo "The value of the 'username' cookie is: " . $username;
} else {
echo "The 'username' cookie is not set!";
}
?>
Output:
<?php
<?php
if(isset($_COOKIE['visited'])) {
echo "Welcome back! We're glad to see you again.";
}
else
{
echo "Welcome to our website! It seems like this is your first visit.";
$expiry_time = time() + (365 * 24 * 60 * 60); // 1 year from now
setcookie("visited", "true", $expiry_time, "/");
}
?>
Output: