I am new to php. I am facing problem with sessions. I mean, after I get logged in and I click on any link in the website , its immediately getting logged out. Not sure why.
In chrome console: I entered as : document.cookie , it showing me "", then I got to understand that cookie is somehow getting deleted immediately or some other issue.
This problem exists for below 2 websites.
We have a websites like :
www.mysite.site1.com/folder1
www.mysite.site2.com/folder2
Below is my code of MySite.com/folder1
function MySession() {
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/v/folder1');
session_start();
}
function clear()
{
$_SESSION=array();
session_destroy();
}
Below is my code of MySite.com/folder2
function MySession() {
$params = session_get_cookie_params();
session_set_cookie_params($params['lifetime'], '/v/folder2');
session_start();
}
function clear()
{
$_SESSION=array();
session_destroy();
}
Setting the domain for cookies in session_set_cookie_params() only affects the domain used for the session cookie .
So to make all your cookies be available across all sub-domains of your site you need to set your cookies on root domain.
when setting the path that the cookie is valid for, always remember to have that trailing '/'.
CORRECT:
session_set_cookie_params (0, '/yourpath/');
INCORRECT:
session_set_cookie_params (0, '/yourpath');
mysite.site1.com is your base url.
when you switched from www.mysite.site1.com/folder1
to
www.mysite.site2.com/folder2
you'll surely be logged out.
Well, I am able to find out answer for my query:
since in my case I have 2 folders ie., www.mysite.com/folder1 && www.mysite.com/folder2 , then we MUST keep session_name('folder1') for 'folder1' and session_name('folder2') for 'folder2' , otherwise both folders share the same session ID and so user gets logged in automatically in folder2 (assuming if he already got loggedin folder1)
function Session() {
session_name('FOLDER_SID');
session_start();
}
Regarding more info about session_name, here: http://stackoverflow.com/a/7551430/4956785
Related
In the same domain I have two applications running
localhost/app1
localhost/app2
Here is my session management:
Page for check the login:
session_start();
//...check if the login is correct
//if is correct
$_SESSION["SESSION_VALID"] = true;
//redirect to the correct page
//if is not correct
$_SESSION["SESSION_VALID"] = false;
//redirect to the login
A page of my application:
//check the session
session_start();
if(!$_SESSION['SESSION_VALID']){
//redirect to login page
header("Location: ../../login/");
exit;
}
Logout page:
session_start();
session_unset();
session_destroy();
//redirect to the login
header("Location: ../login/");
Now, back to the initial problem. I have already read several questions on Stack Overflow related to this problem. The solution would be to use the session_name("app1") before every session_start().
Ok, but now the problem is another: when I logout from one of the application, how can I set which session should be destroyed? Just call session_name("app1") before the destruction of the session? Is the correct solution? Something like that?
session_name("name_of_the_session_to_destroy");
session_start();
session_unset();
session_destroy();
header("Location: ../login/");
It seems you have two applications on the same domain but want to operate two sessions entirely independently of each other. You are finding that logging off one app logs the user off the other app, but you don't want this to happen.
The solution is to set the session cookie only to be valid for the directory part of the domain for each app. By default, sessions extend across the whole domain, which is why destroying the session in one app affects the other one too.
For example, to log onto app 1, do this at the start of your session:
session_set_cookie_params (60 * 30, '/app1');
Of course, you will need to detect which app you are in, and serve the right path component accordingly. You can get this from a $_SERVER variable.
Read more here.
In the logout button url, you can give a GET parameter like ?app=1 or ?app=2, so you know which app to close. If you know the session name of the app you can close it with the following:
You can use unset($_SESSION['SESSION_NAME']); you unset a specific session.
I tried to look my problem up on the internet and on stack overflow, but didn't find an answer that solved my problem. So I have a back-end system for a website I'm creating for an opensource project. I have now just finished transferring everything over to my online domain and database. After a lot of other problem solving, it works now, except for the logging out.
In my back-end header I have the following url:
<h1>Logout</h1>
The content of the logout.php page is the following:
<?php
session_regenerate_id();
session_start();
session_unset();
$_SESSION = array();
session_destroy();
header("Location: login.php");
?>
Offline, via MAMP this works without any problem. However online it doesn't destroy my session. I can still access all my session variables, which enables me to stay logged in. As I said before, I tried to look for an answer, but I don't seem to find one that fixes my problem. If anyone has a clue what might be wrong, please tell me. Thanks in advance!
EDIT:
This is how I check on every back-end page, wether or not I'm logged in:
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_regenerate_id(true); // regenerated the session, delete the old one.
session_start(); // Start the php session
}
As you see, #paulprogrammer, I do something with cookies. How do I destroy it for sure when I logout?
edit(2):
Ok Thanks paulprogrammer for the pointer. I removed the cookie part from my login check function and turned it onto the following simple function:
function sec_session_start() {
session_start();
}
This doesn't create a cookie and now it does work. I tried to unset the cookie via the stuff the official php manul said # http://php.net/manual/en/function.session-destroy.php but that didn't do it. So that's why I moved to something simpler that works. As not many people besides me are gonna use the back-end and as it seems to work ok, even without cookies, I call it done. This topic can be closed :)
final edit(3):
Ok Thanks to *#paulprogrammer it works now with cookies as well. Now that I know the answer, it only seems logical that you have to do that. Stupid of me. OK so apparently I had to set the name of the session, just like i did in my session. I do this in the beginning, before i start it. The new, updated, code of the log in check function:
<?php
session_name('sec_session_id');
session_start();
setcookie(session_name(), '', 100);
session_unset();
session_destroy();
$_SESSION = array();
header("Location: login.php");
?>
You set the session name in your setup code, but failed to set it in the teardown code. So, during teardown PHP was destroying the default session name, not your custom session name. The custom session name is still available on the request after logout.
Simply use the session_name() function consistently anywhere session operations are being used to ensure the session management is always acting on the correct session token.
In your logout.php:
<?php
session_name('sec_session_id');
session_regenerate_id();
session_start();
session_unset();
$_SESSION = array();
session_destroy();
header("Location: login.php");
?>
i have domain and i created a sub domain as well with the name www.join.domainname.com, now the problem is i start session on the main domain login page that is www.domainname.com/support/login.php
all the pages in same domain working properly with session but when i am trying to check the session
on : www.join.domainname.com/member.php
i am not getting anything i don't know why?? Plz help me to solve the issue, here is the code of www.join.domainname.com/member.php :
session_start();
$session_key = (isset($_SESSION['userid'])) ? $_SESSION['userid'] : 'empty';
echo $session_key;
it return the result empty.
You have to set the session cookie domain to .domainname.com so that it can be accessible to all of its subdomain.
you can use the session_set_cookie_params to do this.
session_set_cookie_params(0, '/', '.domainname.com');
session_start();
Alternatively, you can set the session cookie domain with ini_set
ini_set('session.cookie_domain','.domainname.com');
From my previous experience to make your session usable across domain/sub domain you need to use the session.cookie_domain setting e.g
// Start the session
DEFINE('COOKIE_BASE_DOMAIN_NAME', '.domain.com');
$some_name = session_name("domain-name");
ini_set('session.cookie_domain', COOKIE_BASE_DOMAIN_NAME);
session_start();
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();
}
I have read many forums (including this one) about passing session variables between subdomains, and I can't get this to work. Can someone explain what I am missing?
Step 1
In the php.ini file:
session.cookie_domain = ".mydomain.example"
Verified with phpinfo() that I am using the right php.ini file
Step 2
In page at www.mydomain.example set a session variable $_SESSION['a'], verify that it appears by calling it on the next page (it does). Click link to sub.mydomain.example.
Step 3
Page at sub.mydomain.example checks if session variable is set using:
$a = $_SESSION['a'];
if(!isset($_SESSION['a'])){
echo "Error: Session Variable not available";
}
Unfortunately I am getting my error message. What am I missing?
You must pass the session id as a cookie and set the same session id on the new domain
For example you can use this code
ini_set('session.cookie_domain', '.example.com');
$currentCookieParams = session_get_cookie_params();
$rootDomain = '.example.com';
session_set_cookie_params(
$currentCookieParams["lifetime"],
$currentCookieParams["path"],
$rootDomain,
$currentCookieParams["secure"],
$currentCookieParams["httponly"]
);
if(!empty($_SESSION)){
$cookieName = session_id();
setcookie('PHPSESSID', $cookieName, time() + 3600, '/', $rootDomain);
}
if(isset($_COOKIE['PHPSESSID'])){
session_name($_COOKIE['PHPSESSID']);
}
debugging.
is the thing you're missing.
first of all you have to watch HTTP headers to see what is going on and what cookies actually being set. You can use LiveHTTPHeaders Firefox addon or something. With such info you can find the problem. Without it noone can answer tour question "my sessions don't work"
It can prove your statement of proper domain setting in the session settings. Or disprove it.
It can reveal some other misconfiguring.
It may show you cookie being sent back by the browser - so you can be sure that is server side problem
To see the actual result of your code (instead of guessing based on the indirect consequences) always helps.
So, I went a different direction and used this entry which worked...
session_set_cookie_params(0, '/', '.mydomain.example');
session_start();