php - Unable to unset session variable. It's getting regenerated on page refresh

one text

Solution:

That's because you are refreshing the Form page submit.

It is working like this:

  1. Form page: Submits to another page (Post page).
  2. Post page: $_SESSION['custom_flash_message'] is created. wp_redirect redirects us back to the Form page.
  3. Form page: Shows and destroys $_SESSION['custom_flash_message'] .

All good so far. But when you "refresh" the page you are not actually refreshing the Form page. You are refreshing the Post page. The wp_redirect just makes it look like you are refreshing the Form page. So you are actually refreshing back to step 2 and recreating the $_SESSION['custom_flash_message'] . Try just clicking on the URL in the browser location bar and hit enter. This will reload the Form page, but without a redirect. You will see the $_SESSION['custom_flash_message'] was destroyed.

You can stop this by adding a unique id in the form and testing for it on the Post page.

Add a hidden element in your Form page:

<input type="hidden" name="formId" value = "<?php echo uniqid(); ?>">

This $_POST['formId'] will be unique every time the form is submitted.

Then change your creation code to:

If ( $_POST['formId'] != $_SESSION['formId'] ) {
    $_SESSION['custom_flash_message'] = json_encode( array(
        'class'     => 'success',
        'message'   => 'Changes Saved Successfully !'
    ) );
    $_SESSION['formId'] = $_POST['formId'];
}

Now the Post page will only create the message from a fresh form. If you refresh the page it sends the same formId and the message is not created.

Source