Is it possible to use a session variable, then unset it directly after?
Example:
//====
//Process Form
if ($_POST['Submit']) {
$update = $userSettings->update($_POST);
//If there are form errors
if (!$update) {
//Load the errors into an array
$errors = $update[1];
} else {
//Set the session
$_SESSION['showUpdated'] = true;
//Redirect to this page
header("Location: http://www.mysite.com/settings");
}
}
//==================
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
unset($_SESSION['showUpdated'];
}
So after the form is submitted, if there are no errors:
Currently the problem is, if you unset the session variable straight after; It is as if you have un-set it before the "if exists" part.
Any solutions? Is this even the best way to do it?
Many thanks!
You can set session variables in usual way using string as a key e.g. Session["Key"] = obj; To destroy the object in Session set it to null. Session["Key"] = null. you can clear the user session through the session.
By default, session variables last until the user closes the browser. So; Session variables hold information about one single user, and are available to all pages in one application. Tip: If you need a permanent storage, you may want to store the data in a database.
Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.
Session_destroy() function is used to destroy a session. This function destroys the complete session. To unset a single session variable, we can use the unset() function.
I noticed a small error in the original example that might cause other problems.
unset($_SESSION['showUpdated'];
needs to be
unset($_SESSION['showUpdated']);
Not including that end )
in the unset
will cause an error.
That looks like it should work. Make sure you call session_start() before trying to use the session, and always exit() or die() after a redirect header.
I accomplish what you're doing a little differently. I keep a 'message' element in the session. I'll stick text in like 'Your data was saved', error messages, etc. Then, on each page (actually in a page template class), I check to see if the $_SESSION['message']
is set and not empty. If there's something there, I display the message and set the value to an empty string or null.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With