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 !
Related
I am trying to use session_id() on some php pages, but the id changes between every file and it changes everytime i refresh the page. I placed the following script which should increment on ever reload, but it does not.
session_start();
if (!isset($_SESSION['hits'])) $_SESSION['hits'] = 0;
++$_SESSION['hits'];
echo '<p>Session hits: ', $_SESSION['hits'], '</p>';
echo '<p>Refresh the page or click <a href="', $_SERVER['PHP_SELF'],
'">here</a>.';
In my php.ini file, I have cookies turned on as well as set my save_path tp '/tmp'.
In the actual folder, there are session files... so i know it is not a file writing issue. I have also ensured that every file is utf-8 with bom to ensure consistency.
If there are any other solutions you can think of, please help me solve this. It is driving me insane.
Thanks!!!
The 3 possibilities I can think of for your situation are:
How are you calling session_id()? Include that code in your question. If you're calling it with any arguments it will override the session ID to whatever argument you passed.
Are cookies enabled in your browser? The session ID is sent to the browser as a cookie.
Are you calling session_destroy() at any point? This will delete the session data from the server and cause a new session to be started on subsequent pageviews.
That is because you are creating a new session every time you refresh the page. You must enclose your session start statement in a if.
if(session_id() == ''){
session_start();
}
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.
Basically none of my scripts work without a session regeneration check at the top of the file, this is very strange because I've never had this issue before and I have no idea why it would force me to run this code. Below is my logout, then below that is what I have to put at the top of every single file that touches the sessions in order to make it work. Any ideas on what is wrong?
Logout:
require_once("../Core/Core.php");
if(!isset($_SESSION['LoggedIn']))
Core::ThrowError(13,"",1);
session_destroy();
header("Location: " . Core::$url);
Required to make it work: (Also I'm putting this on every page that the user views (so no things like login script page) )
<?
session_start();
if(!isset($_SESSION['started']))
{
session_regenerate_id();
$_SESSION['started'] = true;
}
?>
Update 1:
After adding session_start() above where I add data to variables I'm now able to put data into the session (Although the session was already started because it's started before you even view the login page) but when I call session_destroy() it returns false as if the session doesn't exist, but then I put session_start() above the session_destroy() and it works fine! This is really dumb whatever it is... Please help.
Update 2:
It appears I can only access session data if I put session_start() before trying to access it even if the session is already stated.
Okay I managed to fix it, I didn't know that "To use cookie-based sessions, session_start() must be called before outputing anything to the browser." so to fix it I put session_start() in the core which is required by everything so everything would call it before trying to access the sessions.
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.