PHP logout system not working. (session_destroy on MAMP) - php

I recently transferred my website from XAMPP to MAMP. The problem is that my logout system is no longer working. The logout widget:
Log Out
My logout page itself:
<?php
session_start()
session_destroy()
header('Location:login.php');
?>
The weird thing is that when I change something to logout.php, such as making it a simple echo statement:
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
I still do not see 'test' in my browser; I just stay at index.php even though I have commented out the header in the page. I am 100% the link path is fine.
Wether or not I alter the logout.php file or not, I can see that the server has NOT deleted the session file in tmp/php. This is weird because I have allowed in MAC OS X everyone acces to read and write to this tmp/php folder.
OS: MAC OS X
SERVER: Apache within MAMP
PHP:5.4.4
BROWSERS: Problem occurs in both Google Chrome & Safari
(This is my maiden voyage with posting a question on stackoverflow, if you tips to improve my questioning, please let me know)

Try using this instead:
<?
session_start();
$_SESSION = array();
header("Location: index.php");
?>
I just clear $_SESSION, and it always works for me

If calling logout.php when it containts the code below does not print test then there is something else wrong and it has nothing to do with the sessions.
<?php
echo 'test';
//session_start()
//session_destroy()
//header('Location:login.php');
?>
You mention that it still shows the index.php, which makes me thing you have a rewrite rule in your .htaccess file which redirects the call from logout.php to the index. Check your htaccess file for any rules.
You can find information about htaccess on MAMP here

These are the essential parts of a logout, assuming that your scripts are using PHP sessions. Note that your logout script causes a parse error because it is missing semicolons at the end of statements. Maybe just a typo.
<?php // RAY_EE_logout.php
session_start();
// CLEAR THE INFORMATION FROM THE $_SESSION ARRAY
$_SESSION = array();
// IF THE SESSION IS KEPT IN COOKIE, FORCE SESSION COOKIE TO EXPIRE
if (isset($_COOKIE[session_name()]))
{
$cookie_expires = time() - date('Z') - 3600;
setcookie(session_name(), '', $cookie_expires, '/');
}
// TELL PHP TO ELIMINATE THE SESSION
session_destroy();
// REDIRECT TO THE HOME PAGE
header("Location: /");
exit;
HTH, ~Ray

Try using output buffer.
<?php
ob_start();
session_start();
session_destroy();
header('Location:login.php');
?>

In my case it had to do with the php code block not being defined correctly. I had <? ?> instead of <?php ?>
Hope this helps someone.

#tom.e.degroot: Last time I checked, "it didnt work" was not an error message. You'll need to describe the symptoms a little more. Please follow the guidance here: http://SSCCE.org and give us something we can install and test on our own servers. Thanks, ~Ray

Related

PHP Session Suddenly Stopped Working For Some Pages

I've bumped into a strange glitch. I had no problems before but now suddenly the PHP session will only work for some pages but not others.
Here is how I use the session:
ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
if(!isset($_SESSION["account"])) {
// session does not exist
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}
The same code does not longer work for some pages. For example I'm able to login just fine and use most of the tools for login. But when I created a new file testSession.php with the same content as shown above. It has lost the session for some reason.
I specifically used ini_set('session.save_path', realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session')); to solve a simmilar problem but now the problem is back... why?
The strange thing about all of this is that the one php script I wanted to trigger has worked before without a problem. What could be the issue here? Why does it suddnely not work for some pages/script, as far as I can tell I've never touched that part of the code, so I didn't even change anything.
I suggest to make a session.php file that you call in every page you need to access to sessions like:
session.php
ini_set('session.use_only_cookies', 1); // secure cookie
session_set_cookie_params(0,'/','localhost',true,true); // duration, path, domain, secure connection, httponly (secure js access)
session_start(); // start session
session_regenerate_id(); // regenerating for security issues
and then include this to your pages:
include 'session.php';
if(!isset($_SESSION["account"])) {
echo "<h1>session does not exist</h1>";
} else {
echo "<h1>session exists</h1>";
}
Make sure that u start session on every page. If you have it dynamicly, make sure that your require 'xxx'; is right. Then try deleting you phpsessionid in webdevelopment tools in chrome. At last, restart your local server - wamp, xampp etc.

Php session doesn't work... can anyone tell me what I'm doing wrong [duplicate]

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session.
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();

PHP: $_SESSION not working [duplicate]

Here are the code of my login page where the login script checks for the authenticity of the user and then redirects to inbox page using header function.
<?php
session_start();
include_once('config.php');
$user=htmlentities(stripslashes($_POST['username']));
$password=htmlentities(stripslashes($_POST['password']));
// Some query processing on database
if(($id_user_fetched<=$id_max_fetched) && ($id_user_fetched!=0)){
$_SESSION['loggedIn'] = 'yes';
header("Location:http://xyz/inbox.php?u=$id_user_fetched");
//echo 'Login Successful';
}else{
echo 'Invalid Login';
echo'<br /> Click here to try again';
}
}else{
echo mysqli_error("Login Credentials Incorrect!");
}
?>
The inbox.php page looks like this:
<?php
session_start();
echo 'SESSION ='.$_SESSION['loggedIn'];
if($_SESSION['loggedIn'] != 'yes'){
echo $message = 'you must log in to see this page.';
//header('location:login.php');
}
//REST OF THE CODE
?>
Now with the above code, the inbox.php always shows the output:
SESSION=you must log in to see this page.
Which means that either the session variable is not being setup or the inbox.php is unable to retrieve the session variable. Where am i going wrong?
Make sure session_start(); is called before any sessions are being called. So a safe bet would be to put it at the beginning of your page, immediately after the opening <?php tag before anything else. Also ensure there are no whitespaces/tabs before the opening <?php tag.
After the header redirect, end the current script using exit(); (Others have also suggested session_write_close(); and session_regenerate_id(true), you can try those as well, but I'd use exit();).
Make sure cookies are enabled in the browser you are using to test it on.
Ensure register_globals is off, you can check this on the php.ini file and also using phpinfo(). Refer to this as to how to turn it off.
Make sure you didn't delete or empty the session.
Make sure the key in your $_SESSION superglobal array is not overwritten anywhere.
Make sure you redirect to the same domain. So redirecting from a www.yourdomain.com to yourdomain.com doesn't carry the session forward.
Make sure your file extension is .php (it happens!).
PHP session lost after redirect
I had the same issue for a while and had a very hard time figuring it out. My problem was that I had the site working for a while with the sessions working right, and then all of the sudden everything broke.
Apparently, your session_save_path(), for me it was /var/lib/php5/, needs to have correct permissions (the user running php, eg www-data needs write access to the directory). I accidentally changed it, breaking sessions completely.
Run sudo chmod -R 700 /var/lib/php5/ and then sudo chown -R www-data /var/lib/php5/ so that the php user has access to the folder.
If you use a connection script, dont forget to use session_start(); at the connection too, had some trouble before noticing that issue.
Maybe if your session path is not working properly you can try session.save_path(path/to/any folder); function as alternative path. If it works you can ask your hosting provider about default path issue.
Just talked to the hosting service, it was an issue at their end.
he said " your account session.save_path was not set as a result issue arise. I set it for you now."
And it works fine after that :)
Maybe it helps others, myself I had
session_regenerate_id(false);
I removed it and all ok!
after login was ok... ouch!
I had similar issue and with the cookie domain:
ini_set('session.cookie_domain', '.domain.com');
the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.
The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.
session_set_cookie_params(0)
I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com
I was also facing the same problem i did the following steps to resolve the issue
I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info
2 After that just changed the permission given below *chown root.apache /var/lib/php/session *
That's it. These above steps resolve my issue
Ensure values you write to your session are simple types. Complex types can cause all session changes to be dropped from memory.
I made the mistake of accidentally setting a session variable with an object value. This prevented the session from serializing and saving. The session appeared to be valid until the page refreshed.
A good way to verify this is to do a var_dump() of $_SESSION and exit() to ensure you are writing exactly what you expect.
echo '<pre>Session: ';
var_dump($_SESSION);
echo '</pre>';
exit();
In my case I could fix the issue by casting my username to string as follows:
$_SESSION['Username'] = (string)$userData->Username;
Cost: 1 nights sleep.
In my case none of above are working then I use ob_clean at the top and it worked like a charm.
ob_clean();
session_start();

Rely on session var not existing to see if cookies are disabled

Logic, the manual and Google say I'm right, but I'm no pro and I like to be 100% sure it is working for all browsers, in any circumstance.
I'd like to check if a user has cookies disabled in his browser. I cannot rely on isset($_COOKIE['test'], because when it's a new user or the user deleted all cookies, there will be no cookie and cookies still can be enabled.
I came up with a very simple solution, but my question is: can I be sure this to works?
If page 1 is: domain/index.php
<?php
session_start();
$_SESSION['id']='Hello';
session_write_close();
header('Location: login');
?>
And page 2 is: domain/login/index.php
<?php
session_start();
if(empty($_SESSION['id'])){
echo 'Turn on your cookies!';
}
?>
Will this always work?
[edit]
To answer my own question: no, this will not work.
I've posted a working solution below.
Thanks to everyone for pointing me in the right direction.
Thanks to everyone for pointing me in the right direction.
My solution works, so I'll share it with you:
index.php
<?php
ini_set('session.use_cookies',1);
ini_set('session.use_only_cookies',1);
ini_set('session.cookie_httponly',1);
$name='test';
if(empty($_COOKIE[$name]){
session_start();
//it seems nessecary to write something in the session
$_SESSION['test']=test;
session_write_close();
}
//redirect to a login page
header('Location: http://example.com/login/');
}
?>
And login/index.php
<?php
$name='test';
if(empty($_COOKIE[$name])){
echo 'Turn on your cookies';
die;
}
?>
See the manual on sessions and cookies

php script don't refreshes in browser

I have the following php code:
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
php code on: successLoginPage.php
<?php session_start();
echo $_SESSION['id'];
Here is problem. When i do all things, i see nothing in successLoginPage.php, after approximately 10 minutes i refresh the page and see correct variable. I tried to clear the cache, ctrl+f5, shutdown the browser and computer, but nothing changes - still need to wait 10 minutes. This problem is exists in chrome and ie8.
How can i solve this problem?
Thanks in advance.
*Edit 1:
I add logout.php page with the following code: session_start();session_destroy();unset($_SESSION); When i log in successfully and receive the proper echo, i push logout link and then log in using another account - all great.
1st question - can i log in via 1st account for the 1st time and via 2nd account for the 2nd time? Is this ok?
2nd question - when i failed to log in, there again i see freeze. If i try to log in with proper account after this, i will see old information about fail login. What i need to do?
It may be somewhat obvious but... is $row['id'] actually a number/string, not NULL? :p You could try
var_dump($_SESSION['id']);
instead of
echo $_SESSION['id'];
Have you tried
session_write_close();
after setting your session variable?
First of all, you are not showing the entire code and in this case it is very important.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
// Mystery ???
When you are calling header('Location: xxx'), it doesn't stop the script, so everything after your header is executed.
You could add the function die to prevent any other code to execute after the redirection.
<?php session_start();
....
$result=$db->query($query);
$row=$result->fetch_assoc();
$_SESSION['id']=$row['id'];
header('Location: http://www.blabla.com/successLoginPage.php');
die(); // No more code executed after this //
Solved the problem.
I deleted all login files and rewrite it from scratch and all seems to work now. Don't know where bug was.

Categories