Unsetting Session the right way - php

I was trying to pass an error message to another page using session variable. On the handler page, the session was initialized in the manner:
function sess() {
$index = $_POST['name'];
$_SESSION['error'] = ($index == '') ? 'name cannot be empty' : $index . " is a good name";
header("Location: http://website-name.com/form");
}; sess();
and on the other page is something like:
if(isset($_SESSION['error'])) {
echo $_SESSION['error']; unset($_SESSION['error']);
};
Now if the form is submitted with an empty field, the error name cannot be empty becomes the value of the session. After that, if the name is then set, the value of the session doesn't change but still returns name cannot be empty.
I've checked to see if it has something to do with the fact that the session was called within a function. got no idea! but found online a way to unset all variable using session_unset. But it's actually one session variable that i want to unset and i found something like session_unset($_SESSION['error']). However, using it did not unset all session but the $_SESSION['error'] doesn't get set anymore within the function unless i use the unset($_SESSION['error']) which doesn't terminate the first session that is set.
So what is actually going wrong? how does unset_session() works differently form unset()? what does it has to do with being inside a function? As far as i can recall, $_SESSION[] is a global variable just like $GLOBALS[] which can be access in any scope.

Related

if and $_SESSION with $POST

I'm sure this is a rookie question but I get undefined index in the $_POST password parameter.
if ($_SESSION['Password'] == $_POST['Password']){
echo 'Hi 2 '.$_SESSION['Password'].'<br>';
}
If I do the following with either with $_SESSION or $_POST, I get the correct echo line.
if (!empty($_SESSION['Password'])){
echo 'Hi 2 '.$_SESSION['Password'].'<br>';
}
Can it be that same parameters cannot be used for both variables ?
First you should understand what is SESSION and POST variables.
SESSION is used to store a session variable that can be accessed throughout the session from any PHP document. POST is used to get any variable that send through the post method.
In the first code snippet you are checking weather the
SESSION['Password'] == POST['Password']
and you are not providing any value through post method and the post variable 'Password' is not defined in your program to that's why you are getting an undefined error.
So to over come this one the best way is to check weather both of the variable has defined or not by using isset function.
if(isset($_SESSION['Password']) && isset($_POST['Password'])){
if ($_SESSION['Password'] == $_POST['Password']){
echo 'Hi 2 '.$_SESSION['Password'].'<br>';
}
}
Provide the value for POST['Password'] through a correct statement then the code will work.
I think you know how to set values for SESSION variable because you are comparing a SESSION variable with a POST variable.

What Does $_session['error'] means in php

I have this php code
if (isset($_SESSION['error']))
{
echo "<span id='error'><p>" . $_SESSION['error'] . "</p></span>";
unset($_SESSION['error']);
}
What Does $_SESSION['error'] means
and unset one please explain
$_SESSION contains all session variables (user ID of logged in user for example). You can set a session variable like this:
$_SESSION['foo'] = 'bar';
And access it later (after multiple page loads still, that's why it's so useful) using:
$foo = $_SESSION['foo'];
echo $foo; //Displays 'bar'
Your code checks if there is a session variable set, and if so display an error and unset the session variable. So I would guess this is to show a one-time error when something went wrong. Using a session variable means you can execute this code on a different page then where the error happened.
$_SESSION['error'] means a an array key of $_SESSION which was generated by you.
It looks in the session, which is a temporary storage that is unique to the user and more often than not is mean to last for the time a user stays on a page in a single "visit session", for a variable (actually rather an array key) called error; it then injects whatever that contains (likely an error message) into a piece of HTML, and after that, it deletes the error from the session storage with unset().
Take a look on the documentation for $_SESSION.

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.

Save Constant GET Variable In A Session

Can some explain to me the best way to store a $_GET variable in a session and the only way the sessions changes is when we verify the data the session is being change to is different from the GET variable.
Currently i have
$tid = clean_get($_GET['tid']);
in a global file which is included on every page the problem with that is the value of $tid will be erased and not stored in a session like i want it to once the user is not on a page with $tid set in the url.
If you get $_GET['tid'] in url then set session again by that new value otherwise restore it from session. Thats it.
session_start();
$tid = (isset($_GET['tid']) && $_GET['tid']!="") ? clean_get($_GET['tid']) : $_SESSION['tid'];
Try this and tell me is it solved?
Use a function like isset() to see if it is being sent. Only then should you replace it:
if(isset($_GET['tid']))
{
$tid = clean_get($_GET['tid'])
// Do stuff to change session data.
}
I think what you are looking for is something like
session_start();
foreach ($_GET as $key=>$value) {
$_SESSION['getValues'][$key] = clean_get($value);
}
This will store all the values in $_GET in the $_SESSION. To retrieve the values later, you just have to use $_SESSION['getValues']['tid'] after calling session_start().
Here I'm assuming that clean_get() is just something that formats and/or escapes data that came in from forms, so calling it on each value before sticking into the session will do all that cleaning when needed.
Note: only call session_start() once, and make sure you do so before doing anything with $_SESSION, otherwise you'll get error messages.

Clear session variable after use

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;
}

Categories