PHP

Store the value of a radio button in a session

What season do you prefer?

What is PHP session?

A PHP session is a way to store information on the server to be used across multiple pages of a web application. Unlike cookies, which store data on the user’s computer, session data is stored on the server. This function must be called at the beginning of your script, before any other HTML tags. Here's a simple example with radio buttons:

Storing the value of a radio button in a session

To store the value of a radio button in a session using PHP, you need to follow these steps:

  1. Start the session using session_start().
  2. Create an HTML form with radio buttons.
  3. Handle the form submission in PHP and store the selected radio button value in a session variable.
  4. Access the session variable to use or display the stored value.

Example Code:

PHP
<?php
if ($_SESSION['season'] == "" ) {
echo 'What season do you prefer?';
} 

else {
echo 'Your prefererence (' . $_SESSION['season'] . ') has been saved in a PHP session. <span id="unsetSeasonSession" class="mwd-remove-section">Click here</span> to remove it.';
}

?>
HTML and PHP
<form method="POST" action="<?php echo $PHP_SELF;?>"> 

  <label class="demo-radio">
  <input type="radio" name="season" value="spring" onClick="submit();" <?php echo ($_SESSION['season'] == "spring") ? 'checked' : ''; ?> />
  <span class="demo-radio-name">SPRING</span>
  </label>
  
  <label class="demo-radio">
  <input type="radio" name="season" value="summer" onClick="submit();" <?php echo ($_SESSION['season'] == "summer") ? 'checked' : ''; ?> />
  <span class="demo-radio-name">SUMMER</span>
  </label>

 <label class="demo-radio">
  <input type="radio" name="season" value="autumn" onClick="submit();" <?php echo ($_SESSION['season'] == "autumn") ? 'checked' : ''; ?> />
  <span class="demo-radio-name">AUTUMN</span>
  </label>
  
  <label class="demo-radio">
  <input type="radio" name="season" value="winter" onClick="submit();" <?php echo ($_SESSION['season'] == "winter") ? 'checked' : ''; ?> />
  <span class="demo-radio-name">WINTER</span>
  </label>

</form>

Use jQuery to make an AJAX request to the PHP file that handles unsetting the session:

jQuery
<script>
 $(document).ready(function(){
  $('#unsetSeasonSession').click(function(){

$.ajax({
  url: 'unset-session.php',  // The PHP script that unsets the session
  type: 'GET',
  success: function(response){
  console.log(response);
  alert('The session has been cleared. Your preference will not be applied after the page is reloaded.');
},

error: function(xhr, status, error){
  console.error('Error:', error);
  alert('Failed to unset session');
}

});
  });
 });
</script>

PHP file that handles unsetting the session:

PHP
<?php
session_start();
unset($_SESSION['season']);
?>