I'm trying to clear the variables from a session and start a new one. From reading around about the variable issue, I think I discovered that this is the right answer:
( $_SESSION = [];)
But when I add that line to my code, on a line by itself within the PHP code, I get a message that "[the server] is currently unable to handle this request," indicating "HTTP ERROR 500."
Without that one command, the page works fine (except that the variables don't behave as I want them to). But every time I activate that line, I get the error. How can I clear the variables without making the server angry?
Update: I have also tried session_destroy(), but it has the same effect. Here is a little more context:
<?php
session_destroy();
session_set_cookie_params(3600,"/");
session_start();
?>
If I comment out the session_destroy() line, the page loads with no trouble. But with that line, I get the error.
Final update for others with this question: I've marked the correct answer. I needed to start the new session before unsetting the variables from the last one.
You should not use session_destroy() before session_start(). Try this:
session_start();
session_set_cookie_params(3600,"/");
session_destroy();
To remove all session variables use:
session_unset();
if you are having issues after destroying your session, then it is likely that your code is trying to access session variables that have not been set. I like to check with isset()
eg
$myVar = "";
if (isset($_SESSION('MyVar')) $MyVar = $_SESSION('MyVar');
Related
on every page (first lines, first code) I have those two lines of code:
define("DIRECT_ACCESS", true);
defined("DIRECT_ACCESS") OR die(header("Location: https://website.com/"));
after those two lines of code, I always do session_start();, I read that session_start() should come as a first thing, before anything. Session_status() shows that session is active and working properly, so I have a couple of questions:
1. Why does the session work if it should be the first line, before other code?
2. Is there anything dangerous that can happen, could something stop working later if I don't put session_start() as the first line of code?
Thanks for your time trying to help me.
I read that session_start() should come as a first thing, before anything.
That statement is basically wrong.
There're a few things to take into account when initialising sessions:
With the default (and recommended) settings, session ID is transmitted through a cookie. Server-side cookies are set through HTTP headers. HTTP headers need to be sent before response body. Thus you need to avoid constructs like this:
echo 'Hello, World!';
session_start();
You cannot use session data before it's retrieved from the persistent storage. That's precisely what session_start() does. So you cannot do this:
$user_name = $_SESSION['user_name'];
session_start();
Some times you may want to close the session in order to unlock the storage. You do that with session_write_close(). Once you do that, session data remains loaded but changes won't persist. So please avoid:
session_write_close();
$_SESSION['user_name'] = 'john.doe';
Other than that, you're free to start sessions whenever you see fit.
Running PHP 7.2.12 on a local Apache server (XAMPP on Windows).
I'm playing around with multiple sessions in PHP to see if I can stash away an open session, play around with a new one, and retrieve the previous session. I'm about to give up and just chalk it up to some kind of file locking thing.
The code that hangs ("connection reset" in Firefox):
//first session
session_start();
$old_id = session_id();
$old_session = $_SESSION;
$id = session_create_id();
session_commit(); //same as session_write_close()
//new session
session_id($id);
session_name('new_name');
session_start();
I don't particularly need any of the code to be this way, but I'm totally lost as to why this hangs due to this:
Comment out any one of the following lines:
$old_id = session_id();
$old_session = $_SESSION;
session_name('new_name');
And it doesn't hang. You can also replace session_create_id() with an alphanumeric string literal and it won't hang. It only seems to hang when all 3 of these optional lines are present, and when using session_create_id() to create a new collision free id. Is there a way to guarantee that it won't hang?
And for anyone who has time, I have another question: What would be the proper way to stash an open session, open/manipulate/save my own session, and then restore the original session?
This works:
//previous session
session_start();
$_SESSION['var'] = 'value';
//try to stash open session
$old_id = session_id();
session_commit();
//open new session
session_id('mySession');
session_start();
//modify and save my session
$_SESSION['var'] = 'mine';
session_commit();
//restore previous session
session_id($old_id);
session_start();
echo $_SESSION['var']; //output 'value'
But I'm afraid that once I start messing with new session names in combo with session_create_id() that I'll run into the hanging problem. Maybe I should check for session id collision without the use of session_create_id()? Or should I just try to piggy-back onto the already open session?
Edit: Maybe the core of what I'm asking is that if I make a PHP class that wants to pass anonymous data to/from the client, and somebody using my class opened a PHP session prior to using my class, what's the accepted way of handling that without stepping on the previous session? Ideally I want to name my session with something unique to the class, ie. not the default 'PHPSESSID'.
You ahe handling Session wrong in first example (you call session_create_id uselessly), it probably cause to hanging. Check logs if something info was here.
Maybe problem can be exhalted when you copy $_SESSION variable to another variable and then close session. As PHP internally works it can cause to unpredictable behavion, because $_SESSION is special type of array.
A novice php learner. I read in a book, and continue to see this at certain forums and tutorials that the statement: session_start() is required to access all global session variables. And yet, multiple solutions offered at stackoverflow suggest using a block of this sort:
if(!(_isset($_SESSION['user']))){
session_start()
}
to be able to access the session variables. Based on my understanding, the session variable $_SESSION['user'] could only have been set at a previous php file by starting a session, and is "only" visible to the current page after the session_start() statement is called. Yet it produces the notice:
Notice: A session had already been started - ignoring session_start().
what am i missing?
Thanks everybody!
Your first block of code should be checking if the session variable is set, rather than the user variable exists in the session:
if(!isset($_SESSION)) {
session_start();
}
However, if you just ensure that you only have a single session_start() per page then you can avoid the "A session had already been started" notice.
session_start() is required to read / set any session variables.
Generally, I would think your code should look like this:
session_start()
if(!(_isset($_SESSION['user']))){
// do stuff here
}
However, the error message implies that you have already started the session elsewhere in your file.
You might have auto_start turned on somewhere (php.ini, .htaccess, etc)?
http://www.php.net/manual/en/session.configuration.php#ini.session.auto-start
Here is a scenario where your error would be triggered :
index.php:
<?php session_start();
require_once('some-page.php'); ?>
some-page.php:
<?php session_start(); // this would make an error when included to index.nl ?>
some-page.php should not have session-start in it as index.php already has started the session.
Also note that going to another page or even closing the tab will not reset your session variables ! so if you set S_SESSION['user'] = 'someuser'; , you close the tab and go to the website again, the session is still there and $_SESSION['user'] would still have someuser as value ! to manualy destroy the session , use session_destroy();
I have learned so much from stackoverflow. I have run into a problem that is strange,
Here it goes.
I have coding that checks if a session has started and if not, I start the session. No problem there
Here is my code
If (session-id = "")
{Session_start();
/* setting session ids */
}
I have an include file that submits a form to the same script (script above)
But when returning to the page via post method, the session gets started again, as if the session stopped.
Edit
If (session_id == "")
The mistake there was a typo.
The problem I originally had was that upon first initialization, I had set session arrays
/* If statement */
$_Session['test'] = ['1','2','3','4','5'];
/* end of if statement */
When user submits data to the same script, the session array will be null, giving an error. The way I solved it was to put session_start on the top of the script and no longer on the if statement. That seemed to solve the problem, thanks for all your input.
i think you want this
if(session_id() == '') {
Session_start();
/* setting session ids */
}
session_id() returns the session id for the current session or the empty string ("") if there is no current session (no current session id exists).
also you Call session_start() more than one there is no problem in that since
session_start() - Start new or resume existing session
in the php version >=5.4.0 you can also use session_status() it
session_status() is used to return the current session status.
Edited
Well it seems that Starting session twice is problem in some case
I am quoting this comment of DaveRandom
If The session is already started. You can't start it again. You can't resume something that isn't stopped. This will stop the message from appearing but I don't understand why you would want to call session_start() in the first place. Note also that session_write_close() doesn't destroy the local $_SESSION variable so make sure you don't try and write to it after you've closed the session.
so you can do this like
<?php
var_dump(isset($_SESSION));
session_start();
var_dump(isset($_SESSION));
session_write_close();
var_dump(isset($_SESSION));
session_start();
codepad
Check whether $_SESSION is set.
isset($_SESSION) or session_start();
http://codepad.viper-7.com/I3i9lv
You need to start the session at the top of every page, just to keep the session. That will not clear the running session, so you can just remove the condition for it to start.
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.