I was working in a project where another developer wrote the code,while a user is login the session_start() as usual and then he is cheking like belows:
if($a['userName'] == $username && $a['password'] == $pwd)
{
$_SESSION['id'] = $a['id']; ?> <script language="javascript"type="text/javascript">window.location="host.php";</script> } else {
$msg= "Invalid Username Password";
}
And when a user want to use the form after couple of seconds its logout and user can not submit data.
I have tried increasing session life time duration:
$sessionCookieExpireTime=8*60*60;
session_set_cookie_params($sessionCookieExpireTime);
And also tried with increasing session lifetime in runtime like below:
ini_set('session.gc_maxlifetime', '3600');
And finally tried by increasing php.ini session lifetime .
Unfortunately those did not work.
One thing I should mention that,there is no session_destroy() for logout issues.
Thanks in advance.
What kind of server are you working on?
On a shared server that runs multiple sites that use a shared session directory the session.gc_maxlifetime is in effect the shortest lifetime of all sites accessing that shared directory.
If the problem is on a development server, find out where the session files are stored and look at what happens to them.
It is also possible that the directory where the sessions are stored is not writeable. In that case the session variable is never stored in the first place.
In all three cases: try to store the session files in a different directory. In code you have to set the session directory with session_save_path() before you call session_start().
The timeout occurs when user idle activity for certain time. There is no way to logout automatically unless using session_destroy.
It may be possible that your code
$a['id'];
returns null by chance.
Also, you need to checkout which page is getting logged out.
Giving the full code may be easy to identify the issue.
Related
session_start();
$_SESSION['user_id'] = 0;
session_regenerate_id();
$_SESSION['user_id'] = 5;
After running the following code, why is my $_SESSION['user_id'] still 0 when I access it later? Am I misunderstanding how session_regenerate_id() is supposed to work? Or is it an issue that I need to address elsewhere?
I can see that two session files have been created in C:\xampp\tmp, but I don't understand why the old file is being used.
My example is me trying to understand why I could not access $_SESSION['user_id'] that I would set after running session_start and session_regenerate_id at the very beginning of my .php file:
session_start();
session_regenerate_id();
$_SESSION['user_id'] = 9; // i am unable to access this because my app is using the old file
Appreciate any help with this.
Didn't you check the session.use_trans_sid php.ini option?
In my php.ini, I have session.use_trans_sid=0 and another suggestion mentioned i do the following as well session.use_strict_mode=1. Still not working after these two edits.
Note: i assume that they are 2 different https/http calls (the two
codes starting with session_start() ... ) Can you see what all is
stored in the 2nd file in the Session before and after you do the
session_start? you can do a print_r($_SESSION) and do it before you
regenerate as well I bet there is some code in between your lines that
you haven't shared, is doing something to the session_start
I actually simplified my code down to the example in my post, and you can see it here. This way, we are not worried about any other code.
I cleared my tmp folder and ran the code. Here are the resulting files with session_regenerate_id() commented out:
First File - https://pastebin.com/mBhQCrF3
addrelease.php output is 9 for 'user_id'
I commented out the line that sets the 'user_id' to 9 to see what happens next time I log on
Second File - https://pastebin.com/QNJ6S7sY
As expected, a new file with 8 as 'user_id'
Now I will clear the tmp folder (and restart server) again and do the same with session_regenerate_id() in the code. More specifically, this is what loginuser.php will run now:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 9;
$response['success'] = true;
$response['username'] = "test";
echo json_encode($response);
exit;
This time, since we regenerate the id, there should be two files after loginuser.php is finished. I can't tell which one was created first, but we can see that one has 'user_id' set as 9 while the other has 'user_id' at 8:
File 1: https://pastebin.com/ba1vAmjd
File 2: https://pastebin.com/H9kDfdvt
After this, the output given by addrelease.php once it's finished is 8.
With the following change to loginuser.php, we can also get an idea of what 'user_id' is before it exits and addrelease.php runs the second session_start() call:
session_start();
$_SESSION['user_id'] = 8;
session_regenerate_id();
$_SESSION['user_id'] = 10;
$response['message'] = $_SESSION['user_id'];
$response['success'] = false;
$response['username'] = "test";
echo json_encode($response);
exit;
I clear tmp folder and restart servers again. This time, 'user_id' output is 10. So we can see that loginuser.php is using the correct file, while addrelease.php does not:
File 1: https://pastebin.com/7MpRMbge
File 2: https://pastebin.com/p6RUxH8F
Hopefully I have supplied enough in response to your comment.
EDIT: Also, I don't know if this is significant, but there is a another activity (dashboard activity) between my login activity and my add release activity that does not trigger a .php file.
I think i know the core issue and have the solution as well.
From the json_encode, i assume that some frontend is querying these php files and a json response is sent. So, the session is being written to multiple times.
After writing to the session, IN EVERY FILE that you write sessions to, but PER HTTP/HTTPS request, please do an explicit session_write_close() https://www.php.net/manual/en/function.session-write-close.php .
So, what i mean is that let us assume you have frontendpage1.php that has the html for the user. If you are writing to sessions in this file, do a session_write_close() at the end. Further, if, as a result of an ajax call or something, you have file1.php, file2.php and file3.php used, where they are all writing to the session, do session_write_close() at the end of the last write of the session.
I remember reading that this good practice when sessions are written to frequently.
I had a similar issue with sessions and this worked well
Remember to do a session_start() at the start of each unique browser request/ajax request
EDIT
2nd Option: I think you have a corrupt cookie PHPSESSID . If you try with a browser that doesn't have any cookies set (for the server that is hosting your files), i bet you see the right session values.
Another way to test is, use the same browser, but just add The only thing I can think of is a corrupt cookie PHPSESSID (the default) or whatever cookie you are using, but just add session_name("myStackOverFlowID"); before session_start(); in both these files. the new session_name is not highly recommended: it is just to test.
EDIT: another option
Do the session_write_close() before regenerating the ID
Thanks
Finally, we know that an Android App is involved!
Check if any part of the App code is storing cookies, etc., in cache
Track time using hrtime(true); (recommended instead of microtime for accuracy) see https://www.php.net/manual/en/function.hrtime.php
If possible, clear out the App data on that android phone and test on a different android phone as well
So, after seeing that session was working correctly on my PC browser, I assumed from there that the issue was perhaps purely with how I set up something in my code for the Android app.
As it turns out, my CookieJar implementation was non-persistent. Using PersistentCookieJar instead, I was able to have cookies persist between my activities on the app.
So for anyone having a similar issue, I would suggest reading through this thread and if nothing works, be sure to check your cookie management implementation for the app.
I have a one page website that uses AJAX to load new php files and update the display.
I start my php session on the main page but when I use ajax to update inner html I need those session variables for the new php file being loaded.
This post is similar to this one: PHP Session Variables Not Preserved . But I checked and my php.ini has session.use_cookies = 1
Main Page PHP:
<?php
session_start();
if(isset($_SESSION['views']))
{$_SESSION['views']=$_SESSION['views']+1;}
else
{$_SESSION['views']=1;}
?>
After User Input I use ajax to call a php file and load a subsection of the page:
<?php
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
Can someone please tell me what important step I am missing? Thank you.
Update: After adding session_id() call to both the main and sub pages I see that both pages have the same Session_ID. However it still cannot pull the session variable and if i do assign it a value the two same name session variables stay independent of one another.
Answer to the question that this question created: I found that I had to set a static session_save path in my php.ini file. With most paid webhosting services they just have a default container for sessions but it is affected by load balancing. What a releif.
I think you're missing session_start() on the page that Ajax calls.
You need:
<?php
session_start();
if(isset($_SESSION['views']))
{ echo "Views: " . $_SESSION['views'];}
else
{ echo "Views: NOT SET";}
?>
You need to start session session_start() in the other PHP file also, the one you are calling through AJAX.
I ran into what i thought was the same issue when running PHP 7 on IIS Server 2012 today.
I had added:
if(!isset($_SESSION))
{
session_start();
}
to the start of each AJAX file but kept recieving the following PHP Notice:
PHP Notice: A session had already been started - ignoring session_start()
A bit of searching lead me to this thread which pointed me in the right direction to resolving the issues I encountered. Hopefully the following information will assist others encountering the same issue.
After checking the session.save_path value was set, in my case C:\Windows\Temp, I thought it best to check the folder permissions match those of the user account I was running IIS under.
In my case it turned out that the directory I had nominated for session storage (in php.ini) did not have the same user (security permissions) assigned to it as the one which was running the IIS site.
Interestingly sessions worked fine when not using AJAX requests prior to me adding the new user permissions. However AJAX did not pick up the session until I had corrected the permissions issue. Adding the same user account that IIS is running under immediately resolved this issue.
In the case of using a paid web hosting service the default session save path is automatically set like this:
http://php.net/session.save-path
session.save_path = "/tmp/"
You need to place the static path to your root folder there.
You're trying to use existing session data from your application in an ajax call. To do that, change how you're calling session_start like so:
// With ajax calls
if (session_status()==1) {
session_start();
}
When making ajax calls to php scripts that need existing session data, use session_start after session_status.
http://php.net/session_status
Need to initialize the session before you trying to login through ajax call.
session_start();
Initialize on the top of the page from where you start the login ajax call.
So that the SESSIONID will be created and stored the browser cookie. And sent along with request header during the ajax call, if you do the ajax request to the same domain
For the successive ajax calls browser will use the SESSIONID that created and stored initially in browser cookie, unless we clear the browser cookie or do logout (or set another cookie)
I'm sorry guys -- after two hours of looking and commenting out and so on, I found one tiny include that was referencing a redirected domain. Somehow this threw everything else off. I'm still not sure why, but by fixing that file to the new domain I was able to fix it. Again, thanks for your help and time in replying to me!
I'm fairly familiar with sessions in PHP, yet I can't tell why these session variables are not sticking on this login system I have. When I log in, I get successfully sent to the index page, but any pages therein I get kicked back to the login page, and also when I reload the index page. I have echoed the session variable $_SESSION['login'] on the index page to make sure its value has accurately been carried over, and it's is there..
... code removed
My wild guess but usually a problem I always encounter in Apache under Linux when dealing with sessions.
Check session.save_path in php.ini. If there's a path there and doesn't exist in your system, create it e.g. session.save_path = "/var/lib/php/session". I'm guessing PHP cannot create session files and thus session won't persist across pages. Give the folder a write permission too, try 0777 (but it's not the best permission as it allows all users). HTH!
Why are you destroying the session during login? This is probably a reason.
session_start();
session_unregister('login');
session_write_close();
session_start();
session_destroy();
You probably might just call session_start() and clear 'login' session value:
<?
$ERRBG="";
$ERRMSG="";
session_start();
$_SESSION['login'] = null;
require_once("db/mysql_connect.php");
.......
Use session_start() only once in the php page at the starting
Do not use session_destroy().
If you want to remove session variable, use unset function.
In case if you want to remove all the variables use session_unset function
Use session_destroy() as the logout operation
Please do this step :
use session_start() at the top of page after <?php just once .
don't destroy session
write var_dump($_SESSION) on in your test-index and write it in that
page when you click on it , it's
redirect to login page ( insert
die() after it ) !
I think session start in your test-index but not in your other page
report result to me !
I have read through the php manual for this problem and it seems quite a common issue but i have yet to find a solution. I am saving sessions in a database.
My code is as follows:
// session
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Then at the top of index.php after the session_start(), i have var_dumped the $_SESSION global and the userID is not in there. As i said ive looked through the PHP manual (http://php.net/manual/en/function.session-write-close.php) and neither session_write_close or session_regenerate_id(true) worked for me.
Does anybody know a solution?
Edit: I have session_start() at the top of my file. When i var_dump the session global before the header redirect, i see the userID in there, but not in the other file, which is in a subdirectory of this script
I know this is an old toppic but I found the solution (for me).
I've put a exit after the header.
$_SESSION['session'] = 'this is a session';
header('location: apage.php');
exit;
This works for me
#Matt (not able to comment yet...): If:
a) It appears in the session before redirect
b) other keys work
80% of the time the problem is register_globals, and use of a equally named variable $userID somewhere (the other 19% is just overwriting in places one doesn't expect, 1% is unable to write/lock session before redirect and stale data, in which case you could try session_write_close() before the redirect). It goes without saying register_globals should be off :P
I haven't heard of this issue, but I haven't used sessions all that much.
With sessions you MUST do a few things and have a few setting setup:
cookies enabled on client side
session_start(), before anything happens
make sure you don't destroy the session(unless they want to logout)
The PHP session id must be the same (relates to cookies)
Another issue could be the $user->id is returning a reference to an object that doesn't exist on the next page. Most likely not, but make sure.
If I saw your code I could help you a lot more. But when debugging check the session key with session_id() and make sure it's the same. If you could try that then tell me I could keep helping.
I too would like to know how this ends up for when I get back into sessions.
You should start the session before using the session array.
PHP Code,
session_start();
$_SESSION['userID'] = $user->id;
header('Location: /subdirectory/index.php');
Have you got an session_start(); on the top?
Not tested but cant you do something like this:
session_start();
$_SESSION['userID'] = $user->id;
if( $_SESSION['userID'] == $user->id )
{
header('Location: /index.php');
}
I never have this Problem before, interesting
userID does not have any keyword status.
Only reason to me, is $_SESSION['userID'] is being overwritten or deleted somewhere.
Make sure you use session->start() in all the files you want to add/access the session.
One important thing ( which may not be applicable in your case ) is, if the session is being handled using cookie, cookie can be made to be accessible only under certain directory and subdirectories under that.
In your case anyhow, subdirectory will have access to the session.
Make sure both pages are the same php version
(php5, php4 sometimes have different session paths)
I had the same problem recently. I'm writting a customized MVC Website for school and, as everyone told, start_session() must be written in the very first lines of code.
My problem was THE LOCATION of "session_start()". It must be the first lines of your global controller, not the first lines of the view. $_SESSION was not accessible in controller's files because it was only initiated when the server render the view.
Then, I'm using session_write_close() after the header('location: xxx.php') call to keep session variables for the next request.
ex:
globalController.php :
//First line
session_start();
require_once('Model/Database.php');
require_once('Model/Shop/Client.php');
...
logonController.php:
...
//Users is validated and redirected.
$_SESSION['client'] = $client;
header('location: index.php');
session_write_close();
Hope it solved your problems.
This was annoying as hell but I finally figured out a solution.
config.php i had:
include 'session.php';
At the top of session.php, I had:
session_start();
By moving session_start() to the top of the config.php file, viola...
Problem solved!
Another option than killing your script forcefully with exit is to use session_write_close to force the changes to be written to the session store.
This should however not happen if your script is terminating correctly.
As the documentation about session_write_close states:
End the current session and store session data.
Session data is usually stored after your script terminated without
the need to call session_write_close(), but as session data is locked
to prevent concurrent writes only one script may operate on a session
at any time. When using framesets together with sessions you will
experience the frames loading one by one due to this locking. You can
reduce the time needed to load all the frames by ending the session as
soon as all changes to session variables are done.
In my case this only happened during debugging with Xdebug, when I triggered the same script multiple times and thus multiple process tried to manipulate the same session. Somehow the session could then no longer be unlocked.
I've got a simple login system using PHP sessions, but just recently it seems that if you visit pages not in a certain directory (/login/) you will always be flagged as not logged in, even when you are. It seems that my session data is being lost when I change directories (say, to /login/user/).
I don't think I've touched the code myself since the problem appeared, is there something my web host could have done to my PHP installation that would delete the session data, and is there a workaround?
EDIT:
Inside each file that needs authorization, it loads a loginfunctions.php file which calls session_start() and checks the login. Files which work in /login and i copy and paste into /login/user stop working, even though i update all the relevant paths and links.
EDIT2:
Okay, some code.
In the actual pages that are giving me the error, this is the auth. code:
require_once("../../../includes/loginFunctions.php");
$login = new login;
$login->checkLogin(0);
Inside loginFunctions.php is this:
class login{
function checkLogin($requiredAccess){
session_start();
if($_SESSION['accesslevel'] < $requiredAccess || $_SESSION['logged_in'] != TRUE){
die("You don't have access to this area. If you should have access, please log in again. <a href='/login/'>Login</a>");
}
if (isset($_SESSION['HTTP_USER_AGENT'])){
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])){
session_destroy();
die("Bad session. Please log in again. <a href='/login/'>Login</a> ");
}
} else {
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
if (!isset($_SESSION['initiated'])){
session_regenerate_id();
$_SESSION['initiated'] = true;
}
}
}
The $requiredAccess variable is the access level that you need to access this page, so if you have an accesslevel of 3 in the database you can view level 0, 1, 2 and 3 pages. This is specified when the function is called in the main page and is compared to the access level of the current user which is defined in $_SESSIONS when they log in.
I'm getting the error 'You don't have access to this area etc." when i try to access these pages. If i try to print the $_SESSION variables, nothing shows; they appear to be empty. However, if I move the file to the /login/ folder (one level up) and update the links, they work perfectly and all the variables print out fine. This makes me think the code is not the part that's not working, but some setting in my PHP install that has been changed without my notice.
maybe you aren't calling session_start() at the begging of pages not in /login/ ..?
I had a similar problem.
Check you don't have a php.ini file. Removing this sorted the problem out. Still looking ito exactly why. The php.ini file could even be blank and it would stop session data from carrying over to more than one directory...
It's possible that they changed the php.ini setting session.cookie_path.
You should call session-set-cookie-params before you call session_start and make sure you set the cookie path yourself. Set it to the highest level directory you want the session to be valid for. EG if you set it to /login it will be valid for /login and /login/user. If you want your session to be valid for the etire site set the path to be /
i had a similar issue. you may want to use:
<?
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); ?>
or something similar. i know cookie and session variables are a different desired solution, but this was able to clear up my issue.
See here for documentation
Make sure you have the same php.ini file in each directory that you want to access the session variables from.
This is why you shouldn't use directory to make false friendly URLs...
Don't forget to call session_start() every time you need the session.