Error retrieving cookie value in included page - PHP - php

I got a problem, I will explain myself with a representative escenario:
I have two php scripts/pages:
Test1.php:
<?php
include_once('test2.php');
session_start();
$id = session_id();
echo "my session id: " .$id.'<br>';
setcookie("SSID", $id);
test();
?>
Test2.php:
<?php
function test() {
echo "session id on test2 <br>";
echo $_COOKIE["SSID"];
}
?>
This is a representative piece of code of my problem, what I am trying to do is to store my session id in a cookie and retrieve it in the second page to resume my session. I know that this is not necessary. In my test server I dont need to do this, but in the production one this is necessari. I can't change any configuration of the production server so I have to adapt the code to the server's configuration.
My main problem here is that the second script gets the session id stored in the cookie the last time. An example:
1st time executing test1.php I get:
my session id: dg2mjk8ros8ajrj3n6i8oa4gj1
session id on test2
vrulbnvvff23bpmm6qbbqbk960
2nd time executing test1.php:
my session id: cj17k0q08mhgpjn9gf0dt0n9i6
session id on test2
dg2mjk8ros8ajrj3n6i8oa4gj1
as you can see the cookie value retrieved in the test2.php function is the last used, not the current. I'm stuck.
I would appreciate any help, thanks.

Something is wrong with your code or most likely your server setup. You session_id shouldn't change, for some reason your web server is generating a new session every page load. This shouldn't happen it defeats the purpose of even having a session. Is there any other code running or is this it?
The reason your cookie is always the same as the previous value is because the $_COOKIE array is populated before your php code runs, it isn't changed if you create a new cookie in your code.
I tried this same code on my setup and I get the same session_id and same cookie value each time.
I would try to fix your server setup issue but if you can't you can force the session id to be consistent. Do this:
if(isset($_COOKIE['SSID']) {
session_start($_COOKIE['SSID']);
} else {
session_start();
}
Also if the cookie already exists you don't need to create a new one:
if(!isset($_COOKIE['SSID']) {
setcookie("SSID", $id);
}

I finally solved this using only session storage but not before changing some parameters in the production server, I dont know which one, sorry.
I really appreciate all your help.

Related

Session not working for first time, from second time it works

I don't know what is the problem. When I do login for first time after deleting all history and cookies and cache, it doesn't set session to redirected page. But when I do login for second time, session is set to redirected page. Here id the code of First & second page.
First Page
<?php
session_start();
include('includes/connection.php');
$email=$_POST['email'];
$password=$_POST['password'];
$data=mysqli_query($GLOBALS["___mysqli_ston"], "select * from user_registration where email='$email' and password='$password' ");
$data1=mysqli_num_rows($data);
$val=mysqli_fetch_array($data);
if($data1>0)
{
$_SESSION['user_id']=$val['user_id'];
echo "<script>window.location.href='index.php'</script>";
}
else
{
echo "<script>window.location.href='login.php'</script>";
}
?>
Second Page
<?php
session_start();
$val=$_SESSION['user_id'];
echo $val;
?>
session_start(); should be at the very top of both scripts!
Session variables are saved on server and assigned a unique code that are passed to browser in cookies.
Because the cookies are set by the headers they need to be sent before anything else!
Even a whitespace at the top of your script may cause session cookie to be not properly set on browser side.
So always start the both scripts like this:
<?php
session_start();
// Rest of the code....
It looks like they are on top on your question but I think you edited question later to put there.
That's the only reason sessions are not working the first time and they are working on second time.
instead of the echo use
header("Location: index.php");
EDIT
alsosession_start should be declared at the top of the first page because you cant set a session that doesn't exist in the context if you were running it in a console environment you would receive the following error
"$_SESSION['user_id'] does not exist in the current context"
same happening here. is php 5.6 is super strange problem. on some pages work normaly and on one dont. First request is like dont get recognized.. :)
for example: set
#when page load set:
$_SESSION['a']=0;
#then with JS requests increase $_SESSION['a']+=1; and this start working on third request...

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.

regenerate_session_id destroying session information

I have an application that needs to create a new session id at specific times. Right now, this is causing the user to log out because $_SESSION ends up being empty.
It is my understanding that regenerate_session_id() should preserve the session information and just change the session id (meaning that $_SESSION['someVar'] would be available on subsequent requests.
What I'm finding is that $_SESSION is empty on subsequent requests.
I've tried copying the data:
$session = $_SESSION;
session_regenerate_id();
$_SESSION = $session;
but that didn't help. If I comment out session_regenerate_id(); subsequent pages load properly (the $_SESSION array is populated and the user stays logged in).
I have a dev environment that I just set up recently running a newer version of PHP (5.5) and this code is functioning as I would expect it to. I'm not aware of any other differences.
What am I missing? Thanks in advance.
session_start();
$_SESSION['name'] = "mike";
session_regenerate_id();
echo $_SESSION['name'];
outputs 'mike'
I did a little test on my server and it seems to be working fine.
<?php
session_start();
$old = session_id();
$_SESSION['name'] = "mike";
session_regenerate_id();
$new = session_id();
echo $_SESSION['name']."<br/>\n";
echo $old ."<br/>". $new
?>
Here is a sample of the output:
mike
d9oog3vo55936m3088o25qqe27
m6qq99pp1c80mit8e66ho3hfn3
As you can see, it is changing the session id and keeping the session variables in place, as it is supposed to. Perhaps your hosting provider has some funky settings in the php.ini? You might want to look into that.
Alternatively, and it is a bit of a hassle, couldn't you create a cookie with a key that will log them back in immediately after it logs them out, then delete the cookie?
After a good nights rest, it occurred to me that you probably have some header issues. Sessions are only valid within the same domain they are set in, so for example, if you set the session variable in www.example.com, then use a header redirect to header("location:example.com");, your session variables will be blank, as they aren't set for that domain, they are set for www.example.com. I would check through your code and see if that is the issue, as you say, it is working fine in your sandbox.

Working with SWFUpload and PHP sessions issue

I am using the jquery addon swfupload.
This addon, SWFUpload works with the php file upload.php (sends the uploaded file info to it and the php saves to dir).
Now my issue is that in every page on my site i have included page_protect();
This starts sessions checks and sets session variables such as userID.
Now in upload.php i wish to output example. "OK id 123, you made it!!"
the id 123 should be the $_SESSION['userID'] outputted there. I tried to output this, but its like theres nothing in $_SESSION['userID'].
I dont understand, it works on all my other pages.
But it seems like the SWFupload when it uses flash to read and execute upload.php the session is another/disappears and cant get the variables?
Are there a explanation for this? How can i fix this?
Update
I tried to make a html normal file form with action="upload.php" and made upload.php to submit the session_id(). When i did this i got the same id as my other sites and my variable userID worked just fine!
Then i tried to set debug to true on swfupload and made upload.php output the same, session_id, and this time it was another session_id and NOT like the other, that contain user_ID variable.
So somehow, when it use flash and executes upload.php it starts a completly new session and therefore theres no variables saved in it. Although this is only a theory what i found out so far.
Update
Ok so now I found out that the session_id are being sended in the SWFUpload configuration,
post_params: {"PHPSESSID" : "<?php echo session_id(); ?>"},
And i can see in the upload.php later in the code, after printing session_id() that it actually changes the session id with this:
// Code for Session Cookie workaround
if (isset($_POST["PHPSESSID"])) {
session_id($_POST["PHPSESSID"]);
} else if (isset($_GET["PHPSESSID"])) {
session_id($_GET["PHPSESSID"]);
}
I took this and placed it before i printed out session_id() and now it prints the same session_id() as the one, the variable userID is stored in.
Now I try to output userID once again, but now I just receive Undefined index: userID error, like it has not been set.
I also tried to set another variable than userID, 'test' with value 123, set on the form upload page, and want to output on the upload.php page, and it could not output it.
How can i fix this? please
See http://www.swfupload.org/forum/generaldiscussion/383 for an explanation of the problem.
Essentially SWFUpload doesn't pass your session cookie onto your upload script. A workaround is to pass the session ID as a parameter, or some identifier that can recreate the session when the upload script is called.
The problem is - flash uploader don't know anything about user's session. By default session data is stored as cookie in user's browser and as a file on your server side. To make Flash uploader take care about session do something like this:
{
movie: 'uploader.swf',
id: 'someid',
name: 'someid',
flashvars: 'cookie=' + document.cookie,
}
On server side start session:
$cookies = explode(';', $_POST['cookie']);
// Get your session cookie like
// list($cookieName, $cookieValue) = str_split('=', $_GET['cookie']);
session_name($sessionName);
session_start();
As an alternative you always can add session ID to form's action as you already did.
Default SWFUpload sends files one by one to upload.php - and then submit a form to destination page. It's the destination page that the user actually sees, so output anything there naturally won't show in the browser (as it's only seen by the flash application, and forwarded to javascript). Unless you explicitly tell javascript to show the return value from upload.php it won't be visible.
Just like you pointed out the session_id is passed through in the swfupload config by:
// Upload configuration
var settings = {
flash_url: "swfupload/swfupload.swf",
upload_url: "swfupload/upload.php",
post_params: {
"PHPSESSID": "xxx",
"uploadpath": "xxx"
}
So all you have to do is this in your PHP:
if (isset($_POST['PHPSESSID'])){
session_id($_POST['PHPSESSID']);
}
Is the session does not exist, session_id will return an empty string so you can go on from there.
http://nl3.php.net/session_id
Just don't forget to have the parameters in php.ini that set :
session cookies to on
and session.use_only_cookies to off
and on a symfony1.x environnement session are handled this way:
post_params: {
<?php echo "'".ini_get('session.name')."':'".session_id()."',"; ?>
}

Sessions Not Working Like They Should PHP

I have a simple form which passes a session variable and it simply fails to load on the second page. I had it running on another server, and after moving it to a new one, it no longer works. I have same PHP version (PHP 5) on both, and it works on one and not on the other - the $_SESSION array is just completely empty.
I checked to see if the session id's were the same, and they are exactly the same on both pages of the form (NOT on both servers, these are obviously different).
session_start(); is the first line of code on all pages of the form.
First Page
session_start();
echo "session id ".session_id();
$_SESSION["gencode"] = $gencode;
Second Page
session_start();
echo "session id ".session_id();
echo $_SESSION["gencode"];
Again, I had it working exactly the same on another server, after the move this part broke, should I be looking for a setting somewhere on the server? Both are Linux, if the session id is echoing that means the same session exists, correct?
Any advice would help.
Check the php.ini on both servers and confirm the session settings are the same.
var_dump($_SESSION) to see what is in the session. You may see something interesting.
Are both pages accessed via exactly the same domain?
Like almost any other PHP function, session_start() can fail, and returns FALSE if it does. Can you check the return value?

Categories