How can PHP sessions be utilized to save checkbox values for users on a website?
To save checkbox values for users on a website using PHP sessions, you can store the checkbox values in a session variable when the form is submitted. This way, the values will persist across different pages until the session is destroyed. When the user visits another page or refreshes the current page, you can retrieve the checkbox values from the session variable and display them accordingly.
<?php
session_start();
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Store checkbox values in session variable
$_SESSION['checkbox_values'] = $_POST['checkbox'];
}
// Retrieve checkbox values from session variable
$checkbox_values = isset($_SESSION['checkbox_values']) ? $_SESSION['checkbox_values'] : [];
// Display checkboxes with saved values
?>
<form method="post">
<input type="checkbox" name="checkbox[]" value="1" <?php if(in_array('1', $checkbox_values)) echo 'checked'; ?>> Checkbox 1<br>
<input type="checkbox" name="checkbox[]" value="2" <?php if(in_array('2', $checkbox_values)) echo 'checked'; ?>> Checkbox 2<br>
<input type="checkbox" name="checkbox[]" value="3" <?php if(in_array('3', $checkbox_values)) echo 'checked'; ?>> Checkbox 3<br>
<button type="submit">Submit</button>
</form>