PHP script to store user preferences in a session variable
PHP Cookies and Sessions: Exercise-9 with Solution
Write a PHP script to store an array of user preferences in a session variable.
Sample Solution:
PHP Code :
<?php
session_save_path('i:/custom/');
session_start();
// Array of user preferences
$userPreferences = array(
"theme" => "light",
"language" => "Spanish",
"notifications" => true
);
$_SESSION["preferences"] = $userPreferences;
echo "User preferences have been stored in the session variable 'preferences'.";
?>
Sample Output:
User preferences have been stored in the session variable 'preferences'.
Explanation:
In the above exercise -
- We start the session using session_start() to initialize the session.
- Create an array $userPreferences that represents the user's preferences. This array contains key-value pairs, where each key represents a preference and its corresponding value indicates the user's choice.
- Assign the $userPreferences array to the session variable $_SESSION["preferences"]. This stores the array of user preferences in the session.
- Finally, display a message to confirm that the user preferences have been stored in the session variable named 'preferences'.
When run this script, an array of user preferences will be stored in the session variable. We can access and use this array across different pages or script executions during the session.
Flowchart:
PHP Code Editor:
Contribute your code and comments through Disqus.
Previous: PHP script to check cookie existence and display a message.
Next: Retrieve and display user preferences in PHP session variable.
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-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics