0

I have a contact form, contact.php, which is processed in form-processing.php.

The form fields are stored in the session array (including ant validation errors) and form-processing.php redirects back to contact.php on error or success.

On success, a thank you message is displayed (instead of the form) on contact.php and the session is deleted using session_unset() followed by session_destroy(). The blank form should then display again on refreshing the page (since the session array will be empty).

However, the data in the session persists even after being unset and destroyed. How can this be? I've confirmed the session is deleted by performing a var_dump before and after the session_unset(); session_destroy(); on the contact.php page. So, after the first time completing form, the thank you message is always displayed.

contact.php:

session_start();

if ( $_SESSION['success'] ) {
    // display thank you message
    session_unset();
    session_destroy();
} else {
    //display form
}

form-processing.php:

session_start();

//get $_POST array, validate, sanitize and save to $_SESSION

//send form contents by email

if ($email_sent) {
     $_SESSION['success'] = true;
}

// redirect to contact.php

Edited to update

This is on a Wordpress installation and there was some issue with where the session was being started. I moved session_start() out of the template file and in to a conditional function in functions.php and the form now works.

James
  • 311
  • 5
  • 17

1 Answers1

0

This should completely destroy the session:

session_unset();
session_destroy();
session_write_close();
session_regenerate_id(true);
if (isset($_COOKIE[session_name()])) {
    setcookie(session_name(), '', time()-42000, '/');
}

You can also do:

$_SESSION = [];
Zach Abrams
  • 93
  • 1
  • 7
  • Thanks, but this simply doesn't work (in this case) - I can perform a `var_dump` after using your code above to confirm that the session is "empty" only for it to be "regenerated" with the original data on page refresh. – James Apr 27 '18 at 08:04
  • Also clear the cookie before running session_destroy() : if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); } – Zach Abrams Apr 27 '18 at 20:15