Php sessions weird behavior - php

My tmp directory is not accessible by php.Hence, sessions can't really work(And they don't)
but in this case, they do for some unknown reason.
Here's the scenario,
I have a page index.php which verifies a users credentials and sets session variables and redirects the user to panel.php
if($verified)
{
$_SESSION['unid']=$unid;
$wel="Welcome :";
$_SESSION['una']=$user;
$_SESSION['level']=$lev;
$_SESSION['pas']=$pass;
$_SESSION['wel']=$wel;
header("location:panel.php");
}
On the panel.php I have the code,
<?php
ob_start();
if(session_id()==''){
session_start();
}
if($_SESSION['una'] == "")
{
header("location:index.php");
}
When i login through index.php, Though the sessions data cannot be read, panel.php opens like it would normally with sessions
On refreshing the page, the sessions are gone and page redirects!
Any explanation for this behavior?
PHP V5.3.10

You always need to call session_start() at the start of your page. It doesn't actually start a new session, but rather initializes the session, including the loading of session variables. It's usually the first thing you do, and usually not only under conditions like in your current panel.php.

Related

Session variables not being created if the user doesn't log out before logging back in

When the user logs in, multiple session variable are created and work perfectly.
When they sign out and log in again it works.
However, when someone quits out of their browser without signing out, the next time they log in no session variables are created.
To sign out, one goes to my logout.php file. The code in my logout.php file is:
<?php
session_start();
session_destroy();
echo '<meta http-equiv="refresh" content=".000001;url=index.php">';
?>
I've tried pasting the code at the start of my index.php (where the login form is) but it doesn't work unless you go to the logout.php file.
Why is this and how do i fix it?
There are some possible situations:
First and main reason:
If you have already started session_start(), server may be dump error, while you trying to create new, if your errors are off, you can't see them.
Second: You do check before session destroy.
You are destroying the session before you are making sure that no session variables remain.
I would delete all of the session variables first before you destroy it, to be safe, because sometimes some get left behind. You can do this like so
if (isset($_SESSION['/*whatever session variables you are using*/'])) {
$_SESSION = array();
session_destroy();
}
Also if you are using any cookies for any reason (though this may not be the case), you need to make sure those are also deleted. something like this:
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(),'',time() - 3600);
}

php session behaving strangely

I have a login.php in the root directory. On valid user login, it executes the following code :
function log_in($id,$keep_login)
{
$_SESSION['auth'] = true;
$_SESSION['id'] = $id;
if($keep_login==TRUE) {
setcookie(session_name(),session_id(),time()+LOGGED_IN_TIME);
}
}
On login.php, in the starting, after including header file (header file contains session_start on first line), I check if a user is logged in using this function :
function logged_in()
{
if(!isset($_SESSION['auth'])||empty($_SESSION['auth'])||!isset($_SESSION['id'])||empty($_SESSION['id']))
{
return false;
}
return true;
}
And if the user is already logged in, I redirect them to profile.php using :
if(logged_in())
{
header('Location: profile.php');
}
I have another file enter.php in /sources/enter.php
The login data from login.php is sent to enter.php . However, in enter.php , I see that the user is already logged in. i.e. logged_in() returns true. Curious about this, I echoed the session id on both login.php and enter.php , and the ids were different.
BTW, I include the header file like this :
$included=TRUE;
require_once 'sources/headers.php';
Does the initialization of $included before session_start (session is started in headers.php) interfere with the session?
Although I AM logged_in, somehow my login.php cannot access my session. Can someone point the problem to me?
UPDATE : when I move enter.php to the root directory (same as login.php), it works like it should. Although for security reasons, I want to move it to /sources/enter.php . Any solution?
ANOTHER UPDATE : just came to know that when I move the enter.php to the root directory,
the files in any subdirectory cannot access the session. The session variables are there, but the session id is different.
AND ONE MORE UPDATE : I just discovered, that the session id in the subdirectories is another id, and contains different $_SESSION variables. What I mean, that root directory has $_SESSION['id']=1 and the subdirectories have $_SESSION['id']=4. Maybe this is because the session id's are different.
Any output by the server before session_start() will interfere and cause your session to fail.
I'm not sure if that's your case but you should add session_start() as the first thing written in your config file. Make sure it's the first thing ever executed on a page.
Sometimes session_start() gets rekt if your file encoding is not utf8-without-bom (you should be using that at all times).
I finally found the problem. It was not in the script. When I used another browser, it worked perfectly. Then i thought that Chrome must have preserved the old session cookie, and was still using it when in the subdirectory. I cleared cache, and it now works. Huh! Such a simple answer it was, I still need to learn. Thanks guys for helping me out!

PHP code not running without session regeneration at the top of the file

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.

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();
}

PHP session_start() function: Why I need it everytime I use anything related to PHP sessions

For logging out a user from my website, I am redirecting the page to logout.php where I am using session_destroy() function. Even there also, logout functionality is not working without session_start() function. By adding session_start() function before session_destroy() function, I am able to logout the user successfully.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
session_destroy() destroys the active session. If you do not initialized the session, there will be nothing to be destroyed.
Why do I need to use session_start() function everytime and in every page where I am doing something related to sessions?
So PHP knows which session to destroy. session_start() looks whether a session cookie or ID is present. Only with that information can you destroy it.
In the default configuration, PHP Sessions operate off of the hard disk. PHP asks you to explicitly tell it when you need this support to avoid unnecessary disk IO.
session_start() also tells PHP to find out if the user's session exists.
session_start() creates a session or
resumes the current one based on a
session identifier passed via a GET or
POST request, or passed via a cookie.
as per http://php.net/manual/en/function.session-start.php
Essentially by calling session_start(), PHP reads the header and cross references that session ID to what is on your system(file system/database/etc), which can then populate the $_SESSION that is relavent to that specific user. Which in turn allows you to call session_destroy() because it knows what session to actually destroy.
consider session_start() as your way of telling the php engine.... that you want to work with sessions.
and, as i understand it, always make that to be the first line ever in php page.
I was confused with the usage of session_start(); and every time I was using a session variable, I was calling session_start. Precisely, I had session_start(); more than once on each page (without even calling session_destroy()). For example,
// 1st call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something
}
else
{
// Do something else
}
// .... some other code
// 2nd call
session_start();
if (!isset($_SESSION['UserID']))
{
// Do something totally different
}
else
{
// Do something else totally different
}
This was creating a performance issue for me. So I ended up calling session_start(); just once at the very top of the page and everything seems to be working fine.
You have to call session_start once (and only once) in every file you want sessions to work in.
A common approach allowing you to only call it once is to have a dispatcher file as your index.php; call session_start in here and have this page include others based on the url's $_GET.
<?php
session_start();
if(isset($_GET['page']) && file_exists('pages/'.$_GET['page'].'.php') {
include $_GET['page'];
}
?>
//www.mysite.com/index.php?page=fish will display /pages/fish.php with session access

Categories