My PHP Sessions are giving me yet another headache.
I have just created a log-out page in my PHP code.
when the user clicks on the link, he is logged out of the system.
I got my code from several PHP manuals online.
The code works fine. No problem.............except for this : when the user logs back into my website, the previous session has been wiped out! Meaning, when the "Main page" displays, it is missing almost all the necessary variables (such as : firstname, lastname, etc...........mostly, the user's data, which he creates when he REGISTERS or the first time)
The registration itself is done in my INDEX.PHP file (which is where I initiate the session : SESSION_START()
From there, the user is taken to the LOGIN-PHP file (where he logs in for the first time)
After that, all is well.
However, once he logs out.............and then tried to log back-in, all the variables have vanished. !
I suspect that the problem is caused by the way I wrote my PHP code in the LOG_OUT.php file :
<?php session_start();
unset($_SESSION);
session_destroy();
session_write_close();
header("url=http://localhost/return_to_main_page.html");
die;
exit;
?>
Perhaps, using : UNSET, DESTROY, CLOSE, EXIT, DIE.........all at once, may be a bit of an over-kill??? :)))))
(Kinda like shooting a mouse with a rocket-launcher)
Not sure.
"Any-hoo", my point is :
(a) The entire process works from A to Z, but only IF everything is done in sequence ---- registration, log-in, do-your-stuff, log-out, etc. But, after that, if the user tried to log back in, the session is "cut-off"
(b) Obviously, this is silly. A user should be able to log back in whenever and wherever he wants. (What if he registers his account on a computer at home, and tries to log-in on another computer in Australia? DOH !)
I can't find anything similar anywhere on google, or such. My guess would be : my problem is so silly, and hence the solution is too obvious, that nobody has ever encountered this before
Doing session_destroy() and unset ($_SESSION) and etc. may be a little overkill.
instead, just do:
<?php
session_start();
session_destroy();
header ('location:http://localhost/return_to_main_page.html');
?>
That's what I do in my logout scripts.. It should work.
If not, let me know.
Related
Sorry if this is a silly question but lately I've been designing a site for a client and something strange has been happening with my sessions.
The site has a PayPal button which redirects the user to PayPal so they can confirm a payment, before being redirected to the site again.
Before the user is redirected, a load of session variables are saved. Some of them are to do with PayPal, others are to do with things on my site such as a variable to determine which user is logged in, their shopping cart items, etc.
Now, here's where things have been going wrong...
The user is redirected from checkout.php to PayPal. Before they're redirected, all session variables for the site are present (shown by var_dump and print_r). This is fine.
The user returns from PayPal to orderreview.php, but var_dump and print_r now show that the site session variables are missing, but all PayPal ones are there.
I fixed this problem by removing "session_start();" from the top of orderreview.php.
So my question is, why did removing that line fix the issue? Why wouldn't it work before?
I thought I understood PHP sessions but clearly I don't understand them as well as I thought.
I'd read this somewhere:
"As of PHP 4.3.3, calling session_start() while the session has already been started will result in an error of level E_NOTICE. Also, the second session start will simply be ignored."
So I was under the assumption that calling session_start at the top of the script wouldn't affect anything if a session was already started earlier.
Thanks for any answers, once again I apologise if this is a silly question.
That's may be because that you have been redirected to another site during the process. And while you return from Paypal to your website, session_start() generated a new session id which your previously stored session variables are not linked to.
And when you removed session_start() (I don't think session should work without this on top), it used the old session id and never got regenerated. Hence, old session data are back!
This is just my assumption.
I'm developing a site for someone where users can post problems to a website and the Admin of the company can view the problems and give a solution for it. I use one page that takes care of the login handling and a mysql db. The problem is that i can log in, it shows me another panel(userpanel), but whatever other button i click, it takes me back to the login panel.
It used to work as i was able to post data to my database. but suddenly after some changes on my website, it stopped working (and i can't find the problem anymore.)
When i log in, $_SESSION["LoggedIn"] gets a value and goes to the other panel on the same page with http post. when i click a button there, it seems that $_SESSION["LoggedIn"] is removed again because i check with isset if the user is logged in, otherwise it shows the userpanel.
//check user logged in
if (isset($_SESSION['LoggedIn'])) {
//Problem posted
if (isset($_POST["plaatsen"])) {
//Processing - plaatsen
postProblem();
}
} else {
//do login thing
}
I've attached my code here and i hope anyone can help me out.
Index.php: http://pastebin.com/BZSirUTT
Functions.php: http://pastebin.com/7Hknhm9r
Website: http://php.olvgroeninge.be/~sac.26A-07/php/Oefeningen/Oefening3/index.php (it's in dutch)
Sessions typically don't disappear by themselves. If they do, assuming you did run session_start() first, it can be due to:
The session could not be saved on the server; this can be due to disc space or permission issues. It could also be due to any page output before the session_start() statement. Fortunately, you can see this by heightening the error reporting at the start of your script:
ini_set('display_errors', 'On');
error_reporting(-1);
The session could not be found; for session to perpetuate it requires the session id at every request. Depending on your settings, this can come from the URL (PHPSESSID=xxx) or cookies. In the latter case, you can verify that your browser sends the cookie by whipping up the browser developer tools.
You destroyed the session yourself; calling session_unset or session_destroy will clear and remove the session respectively. Make sure this doesn't happen accidentally.
The session is garbage collected; this normally only happens after some time of inactivity, configured using the relevant ini settings
The session could not be read; just like #1 but for reading.
Hope at least one of these points helps you.
Debugging the session
You can add the following code to all pages to isolate the problem:
echo '<pre>', htmlspecialchars(print_r($_COOKIE, true)), '</pre>';
session_start();
echo '<pre>Session = ', session_id(), '</pre>';
Update
The problem is that the index.php doesn't set any cookies; OP created a separate small test page which does set cookies. Turns out the problem is #2 then :)
All,
This question probably has a very simple answer - something I'm overlooking. But maybe someone can tell me where to look...
I have a PHP page ("index.php") with a very simple login form (e.g., username and password).
When the user clicks the "Submit" button, the form POSTs the values to another PHP page ("login.php"). That page is supposed to confirm the user's credentials, then do the following:
If the user's credentials are not
correct, redirect the user to
error.php, along with an error
message
If the user's credentials ARE
correct, create a session and set $_SESSION['authenticated'] = true, then redirect him to "loggedin.php"
[UPDATE]
Then, on loggedin.php, I check to see that isset($_SESSION['authenticated']) returns true. If it does, then proceed. If not, redirect the user back to index.php.
However, here's what happens. The FIRST time I fill out the form (with valid creds) and submit it, I can see briefly in the URL bar that the user is sent to login.php, then loggedin.php, but then BACK to index.php.
But, if I re-enter the same credentials and submit the info a SECOND time, everything works exactly as it should.
So, in short, it looks like either login.php is not setting the $_SESSION variable the first time through, or that it is, but for some reason, it's not set when I check it for the first time on loggedin.php
Is there some delay between setting the variable on login.php, and having isset() return true on loggedin.php?
Or, is there something else I'm doing wrong?
Here are the relevant (I think) snippets of code:
In login.php:
session_start();
$_SESSION['authenticated'] = true;
header('Location: http://www.mydomain.com/loggedin.php');
In loggedin.php:
session_start();
$authenticated = $_SESSION['authenticated'];
if (!isset($authenticated)) {
header('Location: http://www.footballpoolz.com/mobile/index.php');
die();
}
Many thanks in advance for any advice or insights!
Cheers,
Matt Stuehler
I think I may know the cause of the error. The session has to be linked to the browser and the IP address (this way more than one person can be logged in at a time). This means that the session has to not only be stored server-side, but the client has to have a link to the session as well so you know who they are logged in as when they request data. This session id is shared as part of the header during all HTTP requests.
When you're redirecting the user, though, you aren't giving them a chance to send new headers, are you? You're probably just sending them the new page. This new page never saw a header from them, so it doesn't know which session variable (PHP has hundreds or even thousands of session variables) belongs to them. When you log back in a second time, you are sending a header, and thus you're sending the session ID and PHP knows which session variable is yours.
There are two solutions. The first is to find a way to redirect them that forces them to send a new header. I believe using header("Location: www.mysite.com/newpage.php"); will do this. I may be mistaken.
The alternative is to temporarily pass the session id when you redirect them to loggedin.php so that you know they are logged in for that first page load. After the initial page load, you no longer need to take this extra step since it will be done for you every time they request a page. To pass the session id you just append ?SID=... to your redirect.
http://www.php.net/manual/en/session.idpassing.php
Redirects really slow things down and cause extra server load. What you should be doing is posting back to the index.php page, which will detect if there is a POST or not. Then log the user in and display the contents of the loggedin.php file. No redirects necessary.
After all, you already know that the user is validated, why redirect them to another page where you have to check validation again (which you just did)? This is more of the concept of a "Front Controller" where your index.php acts as a router to load and display different pages. Even if it's just a welcome page when they login. This eliminates any issues with delays.
You are doing a session_start, right?
Instead of using this true . Try to put some value.
like $_SESSION['username']='mattstuehler'
and check
$loggeduser=$_SESSION['username'];
if(!empty($loggeduser))
I dont see any bugs anyway
I've scrapped all the tutorials that have never worked for one reason or another, and decided to roll out my own registration/login feature on my own, and to my surprise it actually works!
But what I don't get is how the logic behind keeping somebody logged in works! Like, once they've logged in, do I just $_POST their data to whatever other page they visit and once they're on the new page $_REQUEST that post data from the URL and display a message like: "yeah, you're still logged in"?
I'm a bit confused atm, so I hope this question doesn't confuse you too.
Let us have we have pages like login.php after_login_page1.php after_login_page2.php
You can follow these simple steps
Set $_SESSION['id'] = $userid //userid from db in login.php
always have session_start() in the successive pages like after_login_page1.php, after_login_page2.php
Check if(! isset($_SESSION['id'])){
header("Location: login.php");
}
at the logout.php page give $_SESSION['id']=''; and do a session_destroy()
The easiest imo is to use a session.
Basically this is PHP automatically setting a cookie (or adding a piece to the url, depending your configuration) on the user system and automatically loading it on each pageview. You can then add data to the session and as long as the cookie didn't expire (or was deleted) and/or you don't destroy the session, you will have that data at your disposal on each pageview the user does.
Take a look here for a small intro to sessions: http://www.htmlgoodies.com/beyond/php/article.php/3472581/PHP-Tutorial-Sessions.htm
Once they have logged in you generally have two options. Store their details or an authentication token (something that will help the PHP on the server know who is who) in a session or store it in a cookie. Both have their perks, but you will need to choose the one that works for you.
If you store data in a session, the user cannot access what you have stored, only your code can. This is helpful if you want to store say, their id or username. You can trust that it would always be their id and username, because they cannot modify it.
With cookies, the user can access and modify them because they are stored on their local machines. Because of this, you need to be a bit more sneaky and hash the users details, then verify who it is with some server-side logic. It's a little more complex.
A session implementation might look like this:
session_start(); //Make sure you call this at the top of EVERY page
if($passwordsMatch){
$_SESSION['user'] = $_POST['username'];
}
//Now we have access to $_SESSION['user'] on every page.
On another unrelated page:
session_start();
print "Welcome, ".$_SESSION['user'];
Easiest way is to "keep users logged in" is to use PHP sessions. When you run session_start();, PHP sets cookie with SESSION_ID in users browser so it can identify this user. After that, you can set any data in $_SESSION array which will be saved in session between page requests.
I have a PHP website I'm maintaining and I've confirmed that this worked at one point.
We have a website utilizing a login system which stores a logged in user's information in a $_SESSION['user'] variable. The site used to log out the user when clicking /logout.php which essentially removed that portion of the session, then header() redirected to the homepage.
As of recently, the /logout.php file with session_start() at the top somehow doesn't see the session information when print_r() is used to output it for debugging purposes.
If I go to another page, I see the session info just fine, but not on the logout page...which is exactly why I cannot remove the session info, because it's not accessible.
I thought $_SESSION was global on the site until the browser was closed. I've never had this happen and I know the session instance was started on this page, so it's weird that it's not showing me the session data.
Any ideas? I'm totally stumped on this one!
Code: /logout.php
<?
#session_start() is inside this file
require_once($_SERVER['DOCUMENT_ROOT'].'/includes/config.php');
unset($_SESSION['user']);
header("location: /");
exit();
?>
The checking of $_SESSION['user'] is site-wide and I call to various items below it when needed for different things. Someone else built this site and I'm trying to debug why it's not working for them all of a sudden.
If the domain/subdomain is the same as the rest of the page, I would say this sounds like a typical session vs. output error. Make sure you have enabled all errors, and display them, as you might have printed output to the client before calling session_start(). This will break the function and making sessions unavailable.
To fix the problem(if it is the case), you should remove all output before session_start. Even a space before <?php will be considered output by Apache(and other). Also make sure you have disabled BOM(Byte Order Mark) in the document(any decent editor will let you change this, just look for something like "Current file setings").
Always remember the first line of your PHP code should be session_start(); and nothing else. If all your going to do is unset the session variables and destroy the session, Try removing the require_once($_SERVER['DOCUMENT_ROOT'].'/includes/config.php'); and add the session_start() and the session_destroy() at the end of the logout.php file and see if it works.
Are you accessing logout.php from the same exact domain that you set the session to begin with (i.e. example.com vs. www.example.com/logout.php)
As for just unsetting specific session data, it would be best to call session_destroy() and then unset your cookies to kill the session.