Retrieve and display user preferences in PHP session variable
PHP Cookies and Sessions: Exercise-10 with Solution
Write a PHP script to retrieve and display user preferences stored in the session variable.
Sample Solution:
PHP Code :
<?php
session_save_path('i:/custom/');
session_start();
if (isset($_SESSION["preferences"]))
{
$userPreferences = $_SESSION["preferences"];
echo "User Preferences:</br>";
foreach ($userPreferences as $key => $value) {
echo $key . ": " . $value . "</br>";
}
}
else
{
echo "No user preferences found.";
}
?>
Sample Output:
User Preferences: theme: light language: Spanish notifications: 1
Explanation:
In the above exercise -
- We start the session using session_start() to initialize the session.
- Check if the session variable named "preferences" is set using isset($_SESSION["preferences"]).
- If the session variable is set, we retrieve its value using $_SESSION["preferences"] and assign it to the variable $userPreferences.
- Display a heading "User Preferences:" followed by a loop that iterates over the $userPreferences array. Inside the loop, we display each preference key and its corresponding value.
- If the session variable is not set, we display the message "No user preferences found."
- When we run this script, it checks if the session variable "preferences" is set. If it is set, it will retrieve and display user preferences. If it is not set, it will display a message indicating that no user preferences were found.
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP script to store user preferences in a session variable.
Next: Set PHP session timeout: 30 minutes of inactivity.
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://w3resource.com/php-exercises/cookies-sessions/php-cookies-sessions-exercise-10.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics