Session for 2 sites folder in one domain - php

I just want to ask for solution, first..is it bad having two sites with same purpose?
So this is the problem, I have two folder that contain the same site structure. I have two team, 1st it's for local researcher and the 2nd it's for international researcher. And I only got one domain, so they not confusing accessing their admin panel. The differences is only by folder name, such as domain_name/folder1 and /folder2. But the things that make me worried is if there are some user trying to change the name folder, for example researcher 1 is giving access to /folder1 but if he change his folder into /folder2 then he can log-in without his/her username and password.
I tried destroy with cookies, but the menu on admin panel cannot be accessed, it turn back on admin panel login. Here's my destroy cookies code:
if (isset( $_COOKIE[session_name()] ) )
setcookie( session_name(), “”, time()-3600, “/” );
$_SESSION = array();
session_destroy();
I tried this also:
session_start();
session_destroy();
header('location:index.php');
But nothing worked, same problem. Any suggestion?
Thank you...

I am considering that you are using same database for both folder users...if yes...then just add one column in database like "registered_user" containing values either local-researcher or international-researcher
now in folder1(local researcher) you can add php code to check...
e.g.
$user = mysql_fetch_array(mysql_query("select * from users where id=".$_SESSION['user_id']));
if ($user['registered_user'] != "local-researcher"){
header (location:index.php);
exit; // Added by Martin, ALWAYS exit (or die) the PHP script once you use
// a header location redirection.
}else{
?>
//Your local researcher page contents...
.
.
.
<?}?>
same vice versa for folder2....

Related

How do I prevent the ability to change the URL and see other users folders

I have a directory of folders and I want to prevent the user named "x" whos files are availiable like this:reports/x/2015/04/ from changing the x to y and seeing all of those folers in y. I have the sessions working so that you need to be logged in to see any folders, but if you are logged in as x you can see the y folder by changing the URL. here is my index.php.
<?php
session_start();
if(!isset($_SESSION['username'])){
header("Location:../../../../login/login.php");
}
require_once('../../../config.php');
require_once('../../../boilerplate.php');
global $smarty;
$smarty->display('general-report.tpl');
There's some things that are inherently bad about doing it this way, but for simplicity's sake, a quick fix is going to be checking to see if the username matches the folder name.
So, looking at your code, you could do something like this.
if ($username == $dir_name) {
$smarty->display('general-report.tpl');
} else {
$smarty->display('error.tpl');
}
Now, as for why you shouldn't be doing it this way...
The logged in username shouldn't really be visible in the URL.
You don't want people to start sharing their usernames around via URLs and then have mischievous people start brute forcing their way into your login system since they know various usernames.
If it were me, I'd have the report URLs all be the same and just have the logged in username determine which user's reports to show.
That way you know it's only visible to that person and even if they share the URL somewhere, their username won't be getting out into the wild.
You can store in $_SESSION a value that represents the user's home. If a user is outside his home directory, he will be redirected into his home. The value `$_SESSION['home'] can be a value stored in the database or it can be the username itself.
You can do something like this:
preg_match('/reports\/([a-zA-Z0-9]*)\//',$_SERVER['REQUEST_URI'],$matches);
if($_SESSION['home'] != $matches[0]){
header('location: reports/' . $_SESSION['home']);
}
Feel free to adjust the regex.
thank you everyone I got it working with this:
<?php
/*===== Start sesstion and include config and boilerplate=====*/
session_start();
require_once('../../../config.php');
require_once('../../../boilerplate.php');
global $smarty;
/*=====Prevents seeing any pages unless logged in =====*/
if(!isset($_SESSION['username'])){
header("Location:../../../../login/login.php");
exit;
}
/*=====Allows only logged in users to see their profiles in path_report=====*/
preg_match('/maintenance_new\/([a-zA-Z0-9]*)\//',$_SERVER['REQUEST_URI'],$matches);
$path_report = explode("/", $_SESSION['path_report']);
if($path_report[0] != $matches[1]){
header('Location: /maintenance_new/' . $_SESSION['path_report'] );
exit;
}
/*=====Renders out page=====*/
$smarty->display('general-report.tpl');

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 session 'stops' for no reason

I have a vbulletin forum. which is located in www.myDomain.com/Forum
I have another in www.myDomain.com/OtherSite/app
I want my Forum logged in users to be identified the other site.
The forum's cookies session path is on the main Domain path /var/www/myDomain
On my site I use
chdir(FORUM_DIR);
include './global.php';
$arr = $vbulletin->userinfo;
to get the session.
The thing is this - It works. I get the users data etc...
and then, it stops working for no apparent reason after a few page loads.
In my view, a possible reason is that I use the code (listed above) twice in my page load... Could this be it?
edit:
more code untile the sesion include, As requested.
edit2:
thanks #VladTeodorescuI have changed all the include to include_once, but stil the same symptoms, the user data is displayed and then, after 15 mins of using, the session "goes away".. (I have checked the forum site, the user is still logged in there)
ini_set('display_errors',1);
error_reporting(E_ALL);
// CONSTS
//PATHS
define('MAIN_DIR', dirname(dirname(dirname(__DIR__))));
define('APP_NAME', 'GoldSig');
define('CLASS_DIR', MAIN_DIR .'/class');
define('APP_DIR', MAIN_DIR.'/'.APP_NAME.'/app');
define('FORUM_DIR', MAIN_DIR.'/Forum');
define('CHAT_DIR', APP_DIR.'/chat');
//commands and trades tables names
define('T_COMMAND', 'commands');
include_once CLASS_DIR . '/Services/Helper/Files.php';
include_once CLASS_DIR . '/Services/Login/Authorize.php';
if (!Authorize::IsLocalhost()){
chdir(FORUM_DIR);
include_once './global.php';
$arr = $vbulletin->userinfo;
}
I was trying to access my domain from myDomain.com/GoldSig/app
and the session's data is stored in www.myDomain.com/GoldSig/app
I get redirected automatically to myDomain.com/GoldSig/app in FF , though..
hard part is over ..

php password protected website

I'm new to web programing and im trying to find a few good examples / tutorials on how to do a decent job of creating a website that requires users to log on to view any pages beyond the main log in page.
so far i've found 1 or 2 that ive tried but i keep running into the same problem. If i just enter the url of the page i want to see manually i can get in like there was nothing there.
Okay, I'll explain how the basic concept goes and a very simple implementation to get things going.
PHP (and most web applications) rely on RESTful services -- which, to our concern at the moment, means every request is not remotely bound to any other request being made - either that being by the same user or others.
So what does that mean?
This means that for every single request, you need to do your checks. You need to make sure if the user has permissions to execute that page, or less severely even see its contents.
How is this achieved?
By many ways, actually. There are lots of techniques used to enforce authorization on web applications but they would essentially both break down to one of two -- either centralized, or decentralized.
-- Centralized
This means all your actions (and controllers) are being handled through a single file. Say index.php. This file would then include or delegate its tasks to other files (that are not runnable on their own via normal requests) based on request parameters. This is a very popular approach, but not exactly straight forward for new developers. Examples of applications that use this approach would have URLS of the type: index.php?do=register, index.php?do=login, index.php?do=showtopic&topic_id=2, and so forth.
A simple implementation of this technique would go like:
<?php
// index.php
define('RUNNING_APP', true);
// 1. place your auth code here, or...
switch ($_REQUEST['do']) {
case 'register':
// 2. or here
include 'inc/register.php';
break;
case 'do_register':
// 2. and here, and before every include.. and so forth.
include 'inc/do_register.php';
break;
}
?>
<?php
// inc/register.php
defined('RUNNING_APP') or die('Cannot access this script directly'); // make sure to break direct access
?>
<form action="index.php?do=do_register">
<!-- form elements -->
</form>
and so forth.
I've documented where the usual auth code should go.
-- Decentralized
Using this approach, however, your auth code should go at the beginning of every single file. URLS of applications of this sort usually look something like: register.php, login.php, and so forth. The main problem here is that you need to perform all auth logic per file, as stated above, and that may be a hectic job if your files increase in amount. A convenient solution is to have that logic in a single file, and include that file (which would kill the request for unauth personel) before any of your logic. A simple example would be:
<?php
// index.php
include('inc/auth.php');
// index logic
?>
<?php
// register.php
include 'inc/auth.php';
// register logic
?>
<?php
// inc/auth.php
$logged_in = false;
if (!$logged_in) {
die ('You do not have permission to access this page. Please login');
}
?>
When logging in using a form, you should check the username and password in the database. The password should be scrambled (usually done using the MD5 hash algorithm), and stored in the database in the same way. You capture the variables, using something like (use some validation to check if the POST variables are valid):
$username = $_POST['username'];
$passwordHash = md5( $_POST['password'] );
The username and hashed password should be stored in your database. You can then check for a match in the database using:
$res = mysql_query("SELECT * FROM users WHERE username='".$username."' && password='".$password."'");
When a user is found, you use sessions to store the user values, which will allow you to get access to a users information across pages. NOTE: session_start() is usually placed at the top of the page, but I'll place it here for readability.
if ( mysql_num_rows($res) ) {
session_start();
session_regenerate_id(); // regenerate session_id to help prevent session hijacking
$row = mysql_fetch_assoc($res);
$_SESSION['logged_on'] = true;
$_SESSION['username'] = $row['username'];
// add more session variables about the user as needed
}
On every page you want to protect, you add the following to the top of those pages:
session_start();
if ( !isset($_SESSION['logged_on']) ) {
header("Location: login.php"); // user is not logged in, redirect to login page
exit;
}
// page content here
There's HTTP Auth:
http://php.net/manual/en/features.http-auth.php
Or you can roll your own with a login form and session tracking:
http://www.php.net/manual/en/book.session.php.
Http auth means the user gets a pop-up dialog window asking for a username and password, it's less usual than the self-rolled version.
Enjoy!
The sites you mentioned are likely bypassable because the pages past the security check don't save and then check for login status on each page. You need to check that a visitor is logged in before access to a page is granted.
I think most users would expect form input for a login. If you want the user to come back and log in with the same account later after their session expires, you'd need a database to store user information.
When storing user information in a database, you should probably not actually store their password, either. For an example:
name password ...
-----------------------------------------------
Johnny '3858f62230ac3c915f300c664312c63f'
Alice '80338e79d2ca9b9c090ebaaa2ef293c7'
.
.
.
Johnny's password is actually "foobar", but the database stores md5('foobar'). When Johnny tries to log in, he enters his username ('Johnny') and his password ('foobar'). In PHP, you hash the password he entered, and call up his password value from the database, resulting in:
if (md5('foobar') == '3858f62230ac3c915f300c664312c63f')
This conditional is true. You can confirm if he logged in correctly, but you're never storing his actual password.
Alice's password is 'foobaz'. She tries to log in, but accidentally types 'foobar', Johnny's password. this results in:
if(md5('foobar') == '80338e79d2ca9b9c090ebaaa2ef293c7')
Which is false. Again, you don't know what Alice's password is, just that she entered the wrong one.
The downside to this strategy, of course, is that you can't tell the user what their password is when they forget it -- you don't know! You can resolve this by letting a user reset their password (to some semi-random string) instead of strait telling them what their password is.

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