Session variable not being saved from $_REQUEST - php

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.

Related

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");

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

Writing to a PHP Session Variable from Ajax

Ok, this is starting to annoy me, as it's quite simply and works elsewhere, but on this current task it doesn't, so here I go!
There is a main page which relies on either a session variable being set or not to display certain information.
Let's say this page is located here: http://dev.example.com/some_page.php
e.g.
if (isset($_SESSION["some_var"])) { /* it's set so do whatever */ }
else { /* not set so do whatever else.. */ }
There is an ajax page triggered by jQuery $.ajax() to call and set this session variable to null to change the action of the main page, let's say it's located here: http://dev.example.com/ajax/some_ajax_page.php
It's code looks like so:
<?php
if (!isset($_SESSION)) session_start();
$_SESSION["some_var"] = null;
When the main page is reloaded after the ajax is triggered, the session var "some_var" is still intact, but if it's echoed after the "null" in the ajax page then it is set to "null".
Basically it doesn't seem to write to the global session, only to the local path.
Does this make sense?
Any help please? Also if you want more clarification with anything let me know!
The session_start() function will handle the attempt to create and persist a session for you, as defined by PHP's configuration, or optionally at runtime if you set your own save handler. Make sure you read the documentation here:
http://us2.php.net/manual/en/function.session-start.php
For your code, you want to make sure to call session_start() at the beginning of any page in which you'd like to save or access session variables. So your page above may look like:
<?php
session_start();
$_SESSION['myvar'] = 'some value';
Then in a different page you can try to access that value:
<?php
session_start();
if ($_SESSION['myvar'] == 'some value') {
// do something
}
That should work fine.
Get rid of the check for session. If this is the only file your calling just do this:
<?php
session_start();
$_SESSION["some_var"] = null;
Also, are you using framework that auto-regenerates session ID on each request? If so, you'll might have problems.
If you have a dev machine to play with and permissions to do so, you can manually delete all sessions in the /var/lib/php/session/ directory. As you use your site, only one session file should be created. You can also inspect that file to see what is getting written and when.
Seems that you are using different sessions vars. One for the AJAX call and another for the normal pages calls. This may occur when you do not init both call in the same way (or using the same starting code that initializes the sessions)
Be sure to session_start() both calls using the same session_id.
// try in both calls
session_start();
echo session_id(); // must return the same id in both calls
Why don't you use unset? It is the proper way to do it.
Turns out the application I was working on had it's own session_handler and if it was not included before requesting the session data, it was always invalid, eventhough it was the same session_id.

Check if session is set or not, and if not create one?

I want to check if a session is currently set, and if so do allow the page to run as normal (do nothing) if not create a session.
I had a look at another SO question, in which the following code was posted:
if ( empty( $_SESSION['login'] )) { } else { }
Would the easiest way to do this be to set something like $_SESSION['a'] for each session, and then run if(empty($_SESSION['a'])) to check if a session exists?
Then again, can you use a session variable without invoking session_start() in the first place, thus making it obsolete (I tried this yesterday, as an echo though, not an if statement to check that a variable was carrying through without realizing that session_start() needed to be invoked before I could echo the variable).
There's probably an easy way that's oft used, I just can't seem to find it.
Any help would be greatly appreciated!
session_id() returns the string identifying the current session. If a session hasn't been initialized, it will return an empty string.
if(session_id())
{
// session has been started
}
else
{
// session has NOT been started
session_start();
}

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