Clear session variable after use - php

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:
Set a session to say the form submission was okay
Reload the page (to prevent re-submitted POST data)
If the 'showUpdated' session variable is set, display the "Updated" message
Unset the session variable (so we don't see the message on next reload)
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!

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.

I do this from time to time. I never have any problems with it. But what I would add to yours is an exit() function call after the header redirect.
EDIT: The reason for the exit() is that it will prevent it from processing any further code and will eliminate the possibility of unset before you wanted to check after the redirect.

The header call without an exit after will continue running the page.
header("Location: http://www.mysite.com/settings");
exit;
Using that instead, should kill the page and not unset the session variable on the same page call.

Just check to see if it exists. This is safe to do before it has been defined and will tell you your answer after it has been defined.
if(!empty($_SESSION['showUpdated'])) {

Or you can just set it to false.
if ($_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}
And it looks like you use smaller version of PHP than 5.3, because in 5.3 you'll get notice when you use uninitialized value. So you should use isset function:
if (isset($_SESSION['showUpdated']) && $_SESSION['showUpdated']) {
echo "Settings Updated";
$_SESSION['showUpdated'] = false;
}

Related

Using multiple SESSION variables on a single page not working

On my site, the login.php page (if successful login) will redirect to index.php and will start a session and 2 SESSION variables.
One of the variables started is a success message:
$_SESSION["message"] = "Login successful!";
the second is the user session variable:
$_SESSION["authenticatedUserEmail"] = $email;
the problem is that if I check the variables individually and then try and use them on the index.php page, only the first one that is checked will work.
This following snippet will show the $form_message but it will not show the $_SESSION["authenticatedUserEmail"]:
session_start();
if(isset($_SESSION["message"])) {
$form_message = $_SESSION["message"];
session_unset($_SESSION["message"]);
echo $form_message;
} else {
$form_message = "";
}
if (isset($_SESSION["authenticatedUserEmail"])) {
echo $_SESSION["authenticatedUserEmail"];
}
It does work when I only use one if(isset($_SESSION statement but I don't want to always include both inside the same statement.
I've done an error check:
ini_set('display_errors',1);
error_reporting(E_ALL);
but no errors appear.
Can anyone please suggest why this may not be working or if I am missing something?
Thanks in advance.
session_unset function free all session variable. this is why when you are using session_unset, next session variable is not founded. read the manual please.
http://php.net/manual/en/function.session-unset.php
to achieve what you want you can use unset function
unset($_SESSION["message"]);
hope this helps
Your call to session_unset is the problem, you should be simply using unset.
session_unset unsets the whole $_SESSION array.

validation user using $_SESSION in PHP

I have a php page that should only be accessed by admin. I am using a php $_SESSION to validate the user. I have this code segment on top of my page which should only be accessed by the admin
if (!isset($_SESSION["uname"])) {
header("Location:../error.html");
exit;
}
if ($_SESSION["uname"] != "admin") {
header("Location:../error.html");
exit;
}
uname variable is getting pass to the page correctly, I am sure about that. But my validating process does not work as I expected. any user can access the page.
Is there anything wrong I have done here.
Did you output anything before doing these checks, even a single empty line is enough to prevent redirecting the page using
hearder()
As others stated I'd make sure you do
session_start();
But I have to assume you have the correct session values as you put
"uname variable is getting pass to the page correctly, I am sure about
that. But my validating process does not work as I expected. any user
can access the page. Is there anything wrong I have done here."
So that leads me to the header error, one way to tell is adding.
ini_set('display_errors', 1);
above your "validation checks" this should show any errors like "unable to send headers output already sent" etc.
Did you call session_start() function at beginning.
It would not work unless we call session_start before using any SESSION data.
http://www.php.net/manual/en/function.session-start.php
You probably forgot to call session_start() at the very beginning of the restricted page as well as the page where $_SESSION['uname'] is being set. Also make sure that $_SESSION['uname'] does not contains the value of 'admin' for other logged in users.
Note: You can debug values of super globals like $_SESSION using the print_r() or var_dump() functions.
See the example given below;
Start your session in your index or the desire page
sesstion_start();
Create this function to validate and redirect automatically
function isValidate($value, $autoRedirect = true){
if(empty($_SESSION['uname']) || $_SESSION['uname'] != $value){
if($autoRedirect){
header("Location:../error.html");
exit;
}else {
return false;
}
}
else {
return true;
}
}
Now simply call this method to validate the session by name. For example;
isValidate("admin");
isValidate("user");

Session variable not being saved from $_REQUEST

I think i'm missing something obvious. I have a session started at the very top of my page. Below that i have the following code. The var dump out puts "one" when it is displayed from the requested page. After refresh the var dump out puts NULL. Why is this not getting saved?
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
If you have session_start() at the top of your page, as you claim, then your code should look something like this:
session_start();
if($_REQUEST["page"] == 1) {
$_SESSION["one"] = true;
}
var_dump($_SESSION["one"]);
This should 100% work, no question. There IS something else stopping this from working in your code that you have not supplied. My first guess would be a session destroy of some kind.
First, you need to ensure you start the session before attempting to use it. Secondly, it is recommended that you specify either POST or GET instead of generally using REQUEST. If you want to support either GET or POST, you might do something like this:
// Begin Session Management
session_start();
// Check both GET and POST for the parameter
if($_GET['page'] == 1 || $_POST['page'] ) {
// Modify the session
$_SESSION["one"] = true;
}
// See what we ended up with in the session.
var_dump($_SESSION["one"]);
This works for me, but I'm using memcache as my session session handler. Verify your own session handler in php.ini, and ensure that the session handler is working properly. Also, ensure you are closing the session properly if you are redirecting, setting a new location, or exiting in unusual ways.

PHP redirect to page with variable in URL

I have a page, q.php, that is a user submitted post defined by its id, (for example, q.php?id=1 would be a certain post that uses the $id variable to pull all the rest of the information from the database).
I am trying to code a comment submission on the same page, and account for the fact that a user might not enter anything into the field. If this happens, I want the page (e.g. q.php?id=1) to load again with an error message.
I can do the error message with an empty variable that is then given a value by the php file that the form activates. However, I am having a problem navigating back to the specific post. I tried to use include('q.php?id=$id) where $id is set to a number, but I understand that this is not its purpose and it does not accept variables
What should I be using instead?
EDIT
answer.php (file that the form activates):
require 'q.php';
$_GET['id'] = $id;
$_SESSION['error'] = "Please fill in all of the fields.";
q.php:
if ($_SESSION['error'] !== 0) {
echo "<p style='color: #AA1111;'>".$_SESSION['error']."</a>";
unset($_SESSION['error']); // this isn't happening...
}
If you really must include the page inline, you can always modify $_GET:
$_GET['id'] = $id;
require 'q.php';
But an error message sounds like it could be accomplished with a session variable or a redirect. A redirect could look something like:
header('Location: q.php?id=' . $id . '&error=The+error');
exit();
Then, you check for $_GET['error'] in q.php. Using a session variable for that would be much the same, except instead of adding error as a querystring parameter, you use $_SESSION['error'] and unset it immediately.
You could use header("Location: q.php?id=$id"); exit;, but you would need some other way to send the error message (example: save it in $_SESSION)
You might be able to set the $_GET array how you want it - in this case, $_GET = Array("id"=>$id); then include("q.php"). This is generally considered haxy, though, and may result in problems if you don't use include_once properly.

Am i testing for a PHP $_SESSION variable too soon after setting it?

I have a login that I've implemented with AJAX and the PHP on the backend sets $_SESSION['guest'] before sending the response text back. Then it the javascript on the front end redirects me to the guest page which checks whether or not isset($_SESSION['guest']), but often this results in false, and i'm taken to another page (using my else branch).
I'm wondering if maybe I'm checking for it too early and that's why isset($_SESSION['guest']) results in false. But I make it count down 5 seconds before redirecting to the page that tests for it, so this is what I don't understand.
After it happens a couple of times (i logout and log back in again), it stops failing and I can't get it to fail which obviously doesn't help! Thought that may be a caching/cookie problem but I've cleared all that and it still won't fail again.
Any ideas?
//this is the login script snippet
if($rows == 1){
$_SESSION[$type] = $username; //$type is posted over as guest or client. this is valid right?
$_SESSION[$type.'_id'] = $result['id'];
echo $_SESSION['welcome'] = 'You have logged in successfully.';
}
<?php
//snippet from the guest page. session_start() is invoked within the included 'page_top.php'
include('page_top.php');
if(isset($_SESSION['guest'])){
if(isset($_GET['sect'])){
if($_GET['sect'] == 'photography'){
include('view_album.php');
}
else{
include('404.html');
}
}
else{
include('welcome.php');
}
}
else{
include('403.html'); //i get redirected here!
}
include('page_bottom.php');
?>
edit: i now think that when it fails the session variable just isn't getting set because if i reload my guest page, it results in the 403.html page every time, so it's not a delay, it just doesnt get set.
I don't think you should be echo-ing a variable as you are setting it? That doesn't make any sense to me.
echo $_SESSION['welcome'] = 'You have logged in successfully.';
If $type is being posted over as guest or client, shouldn't it be $_SESSION[$_POST['type']];
or are you setting $type to the POST variable somewhere else in the page?
You must include this at the top of the page (before ANY HTML or whitepace output, and after the < ?php):
session_start();
EDIT:
I know this is an old post. But for anyone that needs it in the future here it is!

Categories