PHP Session not Saving - php

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

Related

PHP Centos : Session not able to store

Hi Today I am facing one strange Problem
After login validation I am storing the user name in session and redirecting it to some other page .
Validation page .
if (mysql_num_rows($sqlQuery) == 1) {
session_start();
$_SESSION['username'] = $login;
print $_SESSION['username'];
header("Location: dialout.php");
}
.
on dialout.php I am trying to print session like
var_dump($_SESSION);
But it doesn't print anything .
some googling I found that problem might be in writing the session directory .
So to check that I wrote one script .
print session_save_path();
if (!is_writable(session_save_path())) {
echo 'Session path "'.session_save_path().'" is not writable for PHP!';
}
else{
echo "writable -------------";
}
From above script I am getting writable.
Just wondering why my I am unable to access the session on dialout.php page
In your Validation page,the following code should be at the top of the file, as first line in your code.
session_start();
It should be included in every page if you want to use session variable.
First, carry out these usual checks:
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
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!)
can all be found here: PHP session lost after redirect
Call session_start function in dialout.php befor accessing session variable like this :
session_start();
var_dump($_SESSION);

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!

Using session variable to use info on different pages

i'm having a bit of a problem. I'm trying to set up a simple webpage with only three .php pages. I want a session variable $_SESSION['userID'] to be set when a user is logged in and I want the index page to show extra info if someone is logged in.
On index.php I want to show some info, if a user is logged in I want to show some extra info.
login.php - simple log in form.
login_exe.php - takes care of database connection and verification.
So this was my idea:
On index.php, check if session is started, if not: start.
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
later on, check if $_SESSION['userID'] contains a value, if so: print a string
if($_SESSION['userID'] != null){
echo "User logged in";
}
On login_exe.php i've almost the same code:
<?php
if (!isset($_SESSION)) {
session_start();
echo "session started";
}
in verification function:
$_SESSION['userID'] = $data['userID'];
header("Location: index.php");
The problem is that a new session is started on every page. How can I fix this and only start the session once? Thanks in advance
You should just put session_start() on top of documents that using sessions. Say, if you have 5 .php files that using sessions, then put 5 times the session_start() on top of them.
This is because session_start() sends headers and headers must be sent before any output (for example, any echo or whitespace).
Then, you should use something like isset($_SESSION["foo"]) and not just the entire $_SESSION array, where foo is something you set previously.
If you dont want sessions at all or need to reset the entire array, just call session_destroy() which effectively destroy the current session. Use unset($_SESSION["foo"]) when you want to get rid of a key.
Finally, you might get weird cases where you cannot read session key you write at. In these cases check what is the path of sessions and if they're writeable, or change their path:
$path = session_save_path(); // what is the path
is_writable($path); // can i write to it?
session_save_path("my/new/path"); // change the darn path;
// put -even- before session_start()!
:)
glad i help
I think the PHP manuals are really good compared to ...ahm, so just read about session_start(). It says:
session_start() creates a session or resumes the current one (...)
so all you need is session_start() very early in your code. This must be executed on every request (maybe as include).
Your code checking the userId looks fine, one important hint here: you should know exactly what isset(), empty() and the like mean in PHP, so always have the comparision of comparison at hand.
You should not ask new answers (edit: questions) in comments. Be as systematic here as you are in coding.
How to end a session:
This gives room for discussion, because there is the session cookie, which is client side, and the session data, which is server side.
I recommend:
$_SESSION = null;
Reason: this will clear all login and other associated data immediately. It leaves the cookie intact, which is normally of no concern, since all associated data is gone.

isset($_SESSION) Not Working on Remote Server

I have a login page where user enters his username ans password. If successful I redirect him to index.php where I start a session:
session_start();
from index.php he can navigate to a different page ("p1.php") and on top of "p1.php" I have this check:
<?php
if(!isset($_SESSION))
{
exit;
}
?>
This works on my local server, but when I deploy this on remote server !isset($_SESSION) always returns true.
What could be happening here?
EDIT: I found on my hosting provider side a request to add this in php.ini:
session_save_path("your home directory path"/phpsessions);
And to create a phpsessions folder in my path.
I did but that didn't help.
I tried to do this as well:
in index.php:
session_start();
if(isset($_REQUEST['lecturer_id']))
{
echo "lecturer_id set";
$_SESSION['lecturer_id'] = $_REQUEST['lecturer_id']; // store session data
}
and in p1.php:
session_start();
if(!isset($_SESSION['lecturer_id']))
{
exit;
}
And the page always exits i.e. session variable is not defined
The server is most likely creating a PHP session silently which your local server is not configured to do.
Try checking for a specific $_SESSION eg $_SESSION['x'] rather than just a $_SESSION.
Edit:
Instead of checking isset($_SESSION) you should check for whatever session variable you set specifically: isset($_SESSION['SESSION_VARIABLE_YOU_SET'])
isset($_SESSION) returns true once session_start() is called, that's why you need to check for the specific $_SESSION variable you set
You'll just need to make sure you have session_start(); at the very top of your p1.php page and any page that uses session data.
Probably the remote server is configured for session autostart. If you can configure this php instance you can check it in php.ini file (session_autostart directive).
Update: Sorry, I did not understand correctly your question. Really, if session autostart is set to "on" session always exists. You can not use isset($_SESSION) to determine if user is logged or not.
I encountered the same scenario and what I did was I unset the first the variable for example, $_SESSION['loggedin']),
I will unset it first using :
session_start();
unset($_SESSION['loggedin']);
then i will comment out unset($_SESSION['loggedin']);
the problem solved.

PHP Sessions data lost when changing directory?

I've got a simple login system using PHP sessions, but just recently it seems that if you visit pages not in a certain directory (/login/) you will always be flagged as not logged in, even when you are. It seems that my session data is being lost when I change directories (say, to /login/user/).
I don't think I've touched the code myself since the problem appeared, is there something my web host could have done to my PHP installation that would delete the session data, and is there a workaround?
EDIT:
Inside each file that needs authorization, it loads a loginfunctions.php file which calls session_start() and checks the login. Files which work in /login and i copy and paste into /login/user stop working, even though i update all the relevant paths and links.
EDIT2:
Okay, some code.
In the actual pages that are giving me the error, this is the auth. code:
require_once("../../../includes/loginFunctions.php");
$login = new login;
$login->checkLogin(0);
Inside loginFunctions.php is this:
class login{
function checkLogin($requiredAccess){
session_start();
if($_SESSION['accesslevel'] < $requiredAccess || $_SESSION['logged_in'] != TRUE){
die("You don't have access to this area. If you should have access, please log in again. <a href='/login/'>Login</a>");
}
if (isset($_SESSION['HTTP_USER_AGENT'])){
if ($_SESSION['HTTP_USER_AGENT'] != md5($_SERVER['HTTP_USER_AGENT'])){
session_destroy();
die("Bad session. Please log in again. <a href='/login/'>Login</a> ");
}
} else {
$_SESSION['HTTP_USER_AGENT'] = md5($_SERVER['HTTP_USER_AGENT']);
}
if (!isset($_SESSION['initiated'])){
session_regenerate_id();
$_SESSION['initiated'] = true;
}
}
}
The $requiredAccess variable is the access level that you need to access this page, so if you have an accesslevel of 3 in the database you can view level 0, 1, 2 and 3 pages. This is specified when the function is called in the main page and is compared to the access level of the current user which is defined in $_SESSIONS when they log in.
I'm getting the error 'You don't have access to this area etc." when i try to access these pages. If i try to print the $_SESSION variables, nothing shows; they appear to be empty. However, if I move the file to the /login/ folder (one level up) and update the links, they work perfectly and all the variables print out fine. This makes me think the code is not the part that's not working, but some setting in my PHP install that has been changed without my notice.
maybe you aren't calling session_start() at the begging of pages not in /login/ ..?
I had a similar problem.
Check you don't have a php.ini file. Removing this sorted the problem out. Still looking ito exactly why. The php.ini file could even be blank and it would stop session data from carrying over to more than one directory...
It's possible that they changed the php.ini setting session.cookie_path.
You should call session-set-cookie-params before you call session_start and make sure you set the cookie path yourself. Set it to the highest level directory you want the session to be valid for. EG if you set it to /login it will be valid for /login and /login/user. If you want your session to be valid for the etire site set the path to be /
i had a similar issue. you may want to use:
<?
setcookie("TestCookie", $value, time()+3600, "/~rasmus/", ".example.com", 1); ?>
or something similar. i know cookie and session variables are a different desired solution, but this was able to clear up my issue.
See here for documentation
Make sure you have the same php.ini file in each directory that you want to access the session variables from.
This is why you shouldn't use directory to make false friendly URLs...
Don't forget to call session_start() every time you need the session.

Categories