Is this an issue with my PHP Session? - php

I am using sessions to log users into my site.
The login form sends the input to a login-exec file which then queries the db and validates the login info. I have placed session_start(); at the beginning of the login-exec file and then used the below snippet to write data to the session:
session_regenerate_id();
$member = mysql_fetch_assoc($result);
$_SESSION['SESS_MEMBER_ID'] = $member['id'];
$_SESSION['Username'] = $member['username'];
$_SESSION['key'] = $member['Serial'];
session_write_close();
header('Location: account.php');
at the beginning of the account.php file i have required the auth.php to validate the session.
account.php: require_once('auth.php');
auth.php:
<?php
//Start session
session_start();
//Check whether the session variable SESS_MEMBER_ID is present or not
if(!isset($_SESSION['SESS_MEMBER_ID']) || (trim($_SESSION['SESS_MEMBER_ID']) == '')) {
header("Refresh: 5; url=login.php");
//echo $_SESSION['SESS_MEMBER_ID'];
die("Access Denied!");
exit();
}
?>
Always the first time logging in it returns access denied. When the script redirects back to the login page and I try again it always works... I have saved my php files in UTF-8 Without BOM as I originally thought there was leading white space before the session was started. That did not fix the issue and I really can't figure this out.
Any ideas as to why this is happening?

I believe the issue was the redirection url in my login-exec.php script. For example:
If I loaded the login.php script by going to http://www.mydomain.com/mysubdirectory/login.php and the header redirect in login-exec.php was pointing to http://subdomain.mydomain.com/account.php the PHPSESSID was being regenerated because the domain changed.
So I changed the header redirects to account.php instead of the full url and this resolved the issue.
I could have used a full URL either subdomain.mydomain.com or mydomain.com/subdirectory/ but in doing so would of restricted the user and the scripts portability. So simple answer..ensure the domain is staying the same. If it isn't you can set the session name which I am pretty sure would resolve this aswell. However in my case header('Location: script.php'); did the trick.

Get rid of the session_write_close();
If that doesn't solve it, it might be that you are losing the session in the account.php file.
Make a call to session_start(); before requiring the auth.php page.

Related

PHP session_destroy() isn't working

This is frustrating, I've been working with PHP Sessions for a long time and haven't had this problem until now. I'm working on a basic login/logout script using PHP.
Here's what I have for my logout script.
logout.php
<?php
session_start();
unset($_SESSION['email']);
session_destroy();
header("Location:login.php");
?>
And therefore my login.php script has the following code:
login.php
// I send the user to logged_in.php if the session already exists.
if(isset($_SESSION['email'])) header("Location:logged_in.php");
if(pass and username are correct){
$_SESSION['email'] = $email;
session_write_close();
header('Refresh: 1; logged_in.php');
}
Now when I login and I'm redirected to logged_in.php page, form there when I go to logout.php page, instead of being redirected to login.php it goes back to logged_in.php.
Which means that when it arrives to login.php the session still exists and it enters the following if statement in login.php
if(isset($_SESSION['email'])) header("Location:logged_in.php);
Try something like that:
session_start();
// I send the user to logged_in.php if the session already exists.
if(isset($_SESSION['email'])) header("Location:logged_in.php");
if(pass and username are correct){
$_SESSION['email'] = $email;
session_write_close();
header('Refresh: 1; logged_in.php');
}
session_regenerate_id(true) worked for me. I was having the same issue before. It appears that some browsers do not properly delete the session cookie while they are active. Regenerating the ID gives you a fresh session, though you should still of course delete your old session as you have. I'm not quite sure if this is a fix or a workaround, but it works. session_regenerate_id will create a new session variable and delete the old one if you set the parameter to true.

When I check if the session set, I am not able to log in to web site [duplicate]

I have a log in script where I have been able to successfully make users, and log in. Now my issue is that whenever I try to use my method of protecting pages, being seeing if there is a SESSION for 'user' if not it directs you back to the login page.
Here is me checking for the session,
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login");
die("Redirecting to login");
}
Here is where I am setting my session, I am ONLY setting a session_start(); on login.php
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: home?worked=1");
die("Redirecting to: home?worked=1");
session_start();
}
else
{
print("Login Failed.");
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
What this does, is I log in, and it will process and bring me to my home page, then process the header back to the login page acting as if I am not logged in. I tested a false login and it IS telling that its the correct login.
Thanks for any help, I'm pulling my hair out here!
Necro
EDIT
I moved session_start(); to the top of my common.php, and everything is perfect.
You have session_start(); after $_SESSION['user'] = $row;
Actually you have it after a die(); command. Nothing happens after that.
Put session_start(); at the top of PHP in every page (pref common.php since you have one) not just one page.
It would be better to set the session_start() on top
You need to put session_start(); on every page you want to use the session.

why session data not being destroy?

I have some simple php simple scripts. One is to display login user, and the other one is to log out. These are code fragments from a larger file. Anyway, first I executed the login script and enter the user name, the user name showed up fine. Next I executed the logout. If I entered the login page again, i would expected the login_user to be empty, but it is not. The older login_user name is still there. If I clear the cache and bring up the login page again, the login_user is gone. How do I clear the session data for good? Here is the login.php
<?php
session_start();
$_SESSION['myerror']="XXX";
displayLoginUser();
function displayLoginUser()
{
if (isset ($_SESSION['login_user']))
{
echo $_SESSION['login_user'];
}
} // end displayLoginUser
?>
Here is the logout.php
<?php
// NOTE none of the statements below seem to clear the login_user
$_SESSION['login_user'] = " ";
unset ($_SESSION['login_user']);
session_destroy();
header("location: library.php");
?>
TRY THIS:
session_start();
$_SESSION = array();
session_destroy();
will completely destroy the session and all its variables no need to unset() or anything else

PHP Session lost after redirecting

Really annoying problem I can't solve/can only partially solve. Nice juicy one for you pros.
I've got a basic login system set up. Like this:
Login.php:
line 1: session_start();
Check if($_SESSION['logged_in'] == true) header("Location: /controls.php);, incase they've already entered their details.
If they haven't entered them yet, user enters credentials, if valid: $_SESSION['logged_in'] = true;
After database credentials are checked and session is set to true, redirect using PHP header("Location: /controls.php);
Bear in mind, the session is now set.
Controls.php
line 1: session_start();
line 2: if($_SESSION['logged_in'] != true) {header("Location: /index.php");}
Instantly I get taken to index.php ONLY IN CHROME AND FIREFOX.
Also, I have accounttools.php, where the session is again required. Once I try to access accounttools.php, the session is destroyed/unset and any attempt to load accounttools.php results in the header redirect to my /index.php page, again ONLY IN FIREFOX AND CHROME.
I've also got to add in something. If I go back to login.php and re-login, everything works fine and the session gets set properly. Is this a browser-based bug? PHP is executed before any data gets sent to the browser, so how on earth can these browsers act differently if the PHP has already been executed by the time anything reaches the user?
Login file:
// Login.php
<?php session_start();
if($_SESSION['logged_in'] == true)
{
header("Location: /controls.php");
exit();
}
if($_POST['username_login'] && $_POST['password_login'])
{
// Do necessary database work to check credentials (edited out here).
// ...
// Check re-hashed pass against database hash (password checking)
if($make_password == $current_user[0]['password'])
{
// If this is OK login is a success.
$_SESSION['logged_in'] = true;
header("Location: /controls.php");
exit();
}
}
?>
Controls file:
// controls.php
// This page instantly redirects to index.php
<?php session_start();
// Go to homepage if logging out.
if($_POST['logging_out'])
{
unset($_SESSION['logged_in']);
header("Location: /index.php");
exit();
}
// No access unless logged in.
// This session seems to no longer exist at this point. Why??
if($_SESSION['logged_in'] != true)
{
header("Location: /index.php");
exit();
}
?>
Edit: I've discovered something else: If I login and manually enter the URL of the $_SESSION-restricted page, the $_SESSION is not destroyed.
There is some part of the header() redirect that is causing th $_SESSION to become unset/destroyed in Google and Mozilla.
I've also been Googling like crazy and apparently this is a common problem amongs PHP coders. Someone must have a clue what this is?
I see a problem with the way you are redirecting after a successful login: It is a javascript redirect so it will only happen after all the php has finished executing and the result has been sent to the browser. That means that codes after your redirect are executed as well.
I would recommend not outputting anything to the browser until the very end and use the:
header("Location: /...");
exit();
combination everywhere where you want to redirect so that you are sure that nothing happens to your session after the redirect code.
To avoid getting headers already sent problems, I would also recommend getting rid of stuff like:
?>
<?php
like on the first lines of login.php.

PHP Session not Saving

I have this written at the very first line on every page of my website.
include("restd.php");
and restd.php contains the following lines :
#session_start();
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
The problem i'm facing is that when ever i click or do something on my website. it logs me out and takes me to index.php.
im sure its something to do with the session. ive tried every single thing to avoid this problem but i ahve used restd.php because i dont want anyone to copy the url of someone and paste and get into the website.
anyone who is logged in only can view other's pages. if they arent logged in then they'll be redirected to index.php
EDIT : and guys a confusing thing is that all this is working fine on my testing server which is easyPHP-5.3.8.0 but this problem is coming up when i upload all the files to my server.
Your session directory (probably /tmp/) is not writable.
Check with session_save_path() if it is writable.
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
Do you actually set $_SESSION['id'] on a page...
What you are trying to do here is:
Start a session and load the $_SESSION from the session handler
Check if $_SESSION contains key 'id'
Redirect to index.php if $_SESSION['id'] is not set
Do you actually do this in index.php?
session_start();
$_SESSION['id'] = something;
you need declare $_SESSION['id'] :
file1.php
session_start();
$_SESSION['id'] = '123'
file2.php
include 'file1.php'
if(isset($_SESSION['id']))
{
}
else
{
header("location:index.php");
}
In my case I forgot that I had the PHP flag session.cookie_secure set to on, while the development environment was not TLS-secured.
More information about Session/Cookie parameters.
I know this is an old thread, but the following helped me with the same problem after hours of despair. Found on: http://php.net/manual/de/function.session-save-path.php
I made a folder next to the public html folder and placed these lines at the very first point in index.php
Location of session folder:
/domains/account/session
location of index.php
/domains/account/public_html/index.php
What I placed in index.php at line 0:
<?php
ini_set('session.save_path',realpath(dirname($_SERVER['DOCUMENT_ROOT']) . '/../session'));
session_start();
?>
Hopefully this will save you time.
Check maybe your session path does not exist
so you can save PHP session path using:
ini_set(' session.save_path','SOME WRITABLE PATH');
Couple things:
your include file doesn't have the <?php ?> tags, so the content will not be evaluated as PHP
Session_start must be called before you start outputting anything. Is that the case?
You still don't even answer where you SET $_SESSION['id']. $pid = $_SESSION['id'] does not set the session variable. session_start() comes before ANYTHING session related, it's not shown before your include.
I had the same problem and found a work-around for it. If anybody can explain why the session is not read even when the cookie is there, please let me know.
<?php
// logged.php
// The PHP session system will figure out whether to use cookies or URLs to pass the SID
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) && authenticationRoutine(/* Returns true if succesfully authenticated */) ) {
session_id(uniqid("User--"));
session_start();
$_SESSION['id']=session_id();
}
?>
<?php
// Insecure restd.php (The user can forge a stolen SID cookie or URL GET request, but that is inherent with PHP sessions)
if(!isset($_COOKIE['PHPSESSID']) && !isset($_GET['PHPSESSID']) {header('Location: index.php')}
?>
.
[EDIT]
Even though the cookie was there and I prevented starting a new session, the session had not been read and started, so no session variables were available. In this case I check if the session has been started first (not using session_status() because it doesn't exist in PHP 3.5, which for some reason is the most widespread among hosts). If no session has been started within PHP, I check if it had been started before by testing the cookies and GET variables. If a session ID was found, the script resumes the session with that ID. If no ID is available, the user gets redirected to the index.
<?php
// restd.php
if(empty(session_id())) {
if(isset($_COOKIE['PHPSESSID']) && !empty($_COOKIE['PHPSESSID'])) {session_id($_COOKIE['PHPSESSID']);}
elseif(isset($_GET['PHPSESSID']) && !empty($_GET['PHPSESSID'])) {session_id($_GET['PHPSESSID']);}
else {header('Location: index.php'); exit(0);}
session_start();
}

Categories