Problems Setting and Reading Cookie, PHP - php

Greetings,
Been going around in circles trying to figure out why this will not work. Making a low security log-in system using cookies due to an issue with sessions on the device being used. The set cookie works on its own but either is not setting properly in this script or is not being read properly on the auth script. Also, after the cookie should be set, it is not in the browser. Ideas??
Login
<?php
//If passwords match, a cookie is created
if ($pw = $hashedpw) {
$memberID = "1221"; //Pulled from DB
setcookie('MDADMIN_SESS_ID',$memberID,'0','', '.somewhere.com');
header('Location: http://somewhere.com/secure_page.php');
}
?>
Auth
<?php
//Verify that cookie is present
$cookie = $_COOKIE['MDADMIN_SESS_ID'];
if(!isset($cookie)) {
header("Location: http://somewhere.com/failed.php");
exit();
}
?>
The process is as follows: Login Form -> Login Script -> Secure Page (if passwords match) -> Auth Script checked (via include) -> redirect to failed login if cookie not present. When run, it always defaults to the cookie not being present, even though the login script correctly directs to the secure page (logged in successfully).

try
<?php
//If passwords match, a cookie is created
if ($pw = $hashedpw) {
$memberID = "1221"; //Pulled from DB
setcookie('MDADMIN_SESS_ID',$memberID,'0','/', '.somewhere.com');
header('Location: http://somewhere.com/secure_page.php');
exit();
}
?>
You are missing a / for the path.
Also make sure you have an exit(); function after the header; because if you unset the cookie later at someplace then it might also get affect.

try to add / to this line (in $path variable) If set to '/', the cookie will be available within the entire domain
setcookie('MDADMIN_SESS_ID',$memberID,'0','/', '.somewhere.com');

Related

making user redirect if not logged in using php sessions

I am beginner in web development and i am creating my first project. I am using XAMPP, for my php files. I have basically created app.php, sigin.php. So in order to prevent user from directly access my app.php i am using session variables in php. Hence i added the following PHP code just before my app.php.
<?php
session_start();
if(!isset($_SESSION['loginstatus'])) {
header('location:./login.php');
die();
}
?>
And i am setting my session variables in my signin.php like the following:
if($user['username'] == $username && $user['password'] == $password) {
$_SESSION['username'] = $username;
$_SESSION['loginstatus'] = 'success';
echo "success!";
header('location:../app.php');
}
Now i tried accessing my app.php without login, i am still able to access app.php. To check where is the issue i cleared my browser history and cookies, then i tried accessing app.php, then surprisingly it worked i was actually redirected to login page, but as soon as i do first succesfull login, and logout and again try to access app.php without login, i was again able to access app.php without login.
Now for some reason i feel that my browser is saving session variables too, So to check that i wrote a small piece of code and pasted in my app.php:
<?php
var_dump($_SESSION['loginstatus']);
?>
after first successful login my $_SESSION['loginstatus'] is always set to successful. Now as i said i am a beginner, what i learnt is session are stored in server side. So i am totally confused regarding this.
There is a cookie in your webbrowser "phpsessid" wich stores the id of the Session on the server.
In normal cases you destroy the Session, at logout.
session_unset(); to unset all session variables
session_destroy(); destroys the session
The Session will timeout after time X. You can change it, described here -> Link
So if you have a cookie in your Browser with a valid id of a not-timeouted Session you will always be able to log in.
So basically, going to browser setting > privacy and security > more > pre-load pages for faster browsing and searching
I just disabled this default setting from chrome, and it started working as expected.

Just how safe is protecting a page with session_start()?

After my login page all my other pages are inaccessible unless you are logged in. And basically to check if you are logged in I have a simple if else statement:
session_start();
if (isset($_SESSION['id'])) {
// Show the page
} else {
// Ask the user to log in
}
And for the admin pages I have an extra check:
session_start();
if (isset($_SESSION['id']) && $_SESSION['isAdmin'] == TRUE){
// Show the page
} else {
// Unauthorised access
}
Is this a safe way of protecting PHP pages?
Yes it is the safe way. and try to add <?php if(!session_id()) session_start(); ?> at the top of the page because if you have included this page in another page and session is already started in that page, the session will be canceled and this page will be prone to unauthorized users.
It depends.
All PHP session variables are stored on the server side. The moment a session is started by session_start();. PHP sets a temporary cookie on your computer named PHPSESSID set to expire at the end of the browsing session. Using this cookie PHP server assigns values to the session variables. Whenever you log out (i.e, session_destroy();), this PHPSESSID cookie value is made useless
The insecure bit about this is if someone actually stole your PHPSESSID cookie value, the person can simply set this PHPSESSID cookie on their computer and have access to your session without even entering any username or password. However this can be mitigated if you use SSL/HTTPS on your web server. It must be enforced wherever session_start(); is used. You must force SSL/HTTPS where sessions are used. If you just use SSL/HTTPS for login, and HTTP for the rest of the session, this doesn't make you safe as the PHPSESSID cookie is sent in plaintext via HTTP.
As far as I know the only way to compromise PHP's Session mechanism is to steal the PHPSESSID cookie using man-in-the-middle attacks, which can be totally made useless if you have a valid SSL certificate and use of strong cipher suite for your webserver. This cookie can also be retrieved using properly crafted XSS attacks, which can be mitigated if you filter javascript or equivalent from the PHP input to your PHP code using preg_replace with the proper regex.
create one function then call this function when you load your page.. this function return true and false if you login or not and then you can manage your URL redirection..
oR
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
this lucks good..

Remember me feature not working after closing the browser due to wrong cookie name in $_COOKIE array

I am new to PHP. I have tried to implement the remember me feature as explained below.
MysqlSessionHanlder.php -> this implements the 6 session related functions as required by the interface + all functions for "regular login" and login with remember me feature.
login.php -> self explained.
restricted1.php -> if login succeeds, login.php will redirect to this page.
authenticate.php -> This page should be included on every page which requires authentication before being accessed.
db_connect.php -> self explained.
Regular login works well. I am also able to login with remember me checkbox checked, i.e in both cases I am being redirected to restricted1.php. However, once I login using remember me feature -> close the browser -> try to go directly to restricted1.php, I am being redirected again to the login page.
This is because restricted1.php calls first authenticate.php, and this file checks if user is authenticated regular or via auto login existing cookie.
if not, it means that the user tries to access a restricted page without first login which invokes the checkCredentials() function.
authenticate.php code
require_once __DIR__ . '/db_connect.php';
require_once __DIR__ . '/../../classes/MysqlSessionHandler.php';
$handler = new MysqlSessionHandler($db);
session_set_save_handler($handler);
session_start();
$_SESSION['active'] = time();
if (isset($_SESSION['authenticated']) || isset($_SESSION['auto_login'])) {
// we're OK
} else {
$autologin = new MysqlSessionHandler($db);
$autologin->checkCredentials();
if (!isset($_SESSION['auto_login'])) {
header('Location: login.php');
exit;
}
}
However, when I close Chrome, reopen it, and then try to access directly restricted1.php, I am being redirected to login.php.
During debug, I found the following:
Each time user logs in with remember me feature, a function I wrote named persistentlogin() store a new token in the DB + sets a cookie named "auto_login" which includes that token using setCookie() function.
I noticed that the cookie name shown in $_COOKIE super global array is PHPSESSID (default name) although I set the cookie name in my code to be a different one ("auto_login"). I can see BOTH cookies: PHPSESSID and "auto_login" cookie in chrome browser settings, but "auto_login" cookie name is NOT shown in $_COOKIE super global array. I think this is my problem, because checkCredentials() tries to access "auto_login_cookie" as follows:
if (isset($_COOKIE[$this->cookie])) {
$cookie is attribute which is set to 'auto_login' ofcourse.
Why can`t I see the "auto_login" cookie which is set by the setCookie() command in $_COOKIE array?
Thanks,
Qwerty
After several days of debug (!), I found the problem:
Why are my cookies not setting?
It turns out I set the cookie path to something other than '/', which caused this issue.
Thanks anyway :-)
+1 for all the people who put the hard work, and never give up, until they reach their purpose!

PHP - Session mismatch, different id and wrong user, hijack risk and a major security risk

Found a major problem on my website. I found tha if I login with user A. it sometimes kinda does log in but actually doesn't. Then I login with user B -> enter the site. I log out and then go manually back to url where login is needed and it somehow goes in with user A. It seems that I have two (maybe could have more) session_id cookies on different tabs or there is a ghost session_id that comes active I don't know. Pulling my hairs here.
Also found that, lets say I have a user dashboard and test page. With a little going back and forth with different credentials. I get this result:
Dashboard echoes user A's id, test echoes user B's id or not id at all. What the heck I am doing wrong with my sessions?
Login is done with AJAX. Login validation is the same on every page.
COMMON FUNCTIONS:
function validateUser($userid) {
session_regenerate_id();
$_SESSION['valid'] = 1;
$_SESSION['usersid'] = $userid;
}
function isLoggedIn() {
if (isset($_SESSION['valid']) && $_SESSION['valid'] == 1) {
return true;
} else {
return false;
}
}
function logout() {
$_SESSION = array();
session_unset();
session_destroy();
}
LOGIN/DB:
Login page:
session_start();
include 'include_files.php';
if(isLoggedIn()){
header('Location:loginrequiredpage.php');
die();
}
Login page sends username/password with AJAX to an controller php file that uses db functions as included file. It executes usercheckfunc() which checks user from db and then echoes succes or fail back to ajax.
from db functions - part of user check function
//if user found from db and password hash match
validateUser(**ID FROM DATABASE**);
Back in login page if ajax gets success message back, JS send user to login required url.
Here's where mystery sometimes occur The browser acts like if i just logged in somewhere, but the login page is loaded again. Sometimes I can manually go to login required page via address bar. Sometimes if I logout/idle too long etc. and login with different username/password I get in as a wrong user. Entered as user A, See user B's data OR echo different userids on pages or echo id only on other page.
LOGIN REQUIRED PAGE:
<?php
session_start();
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Test page:
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once 'include_files.php';
if (!isLoggedIn()) {
logout();
header('Location:login.php');
die();
}
echo $_SESSION['usersid'];
Is there a "best" way to manage sessions? Help is much appreciated :)
Got rid of the problem by manually setting session cookie parameters everywhere before session_start is executed. Now the session cookie domain doesn't behave unexpectedly. Sorry, no idea why it did that mysterious changeing before.
This cookie parameters sets it to be valid on whole domain. I guess it's no good in situation where you need different sessions on the same domain (different applications etc.). But for me it was the healing patch I needed.
session_set_cookie_params(0, '/', '.example.com');
session_start();

PHP login session wont work on first page load in a NEW window with no cache

I am working on creating a website from scratch and am currently stuck with session stuff.. I know generally how sessions work and how to store things into $_SESSION after session_start() but my main problem is this. After clearing the cache and opening a new window, submitting a login request the FIRST time wont submit correctly and the page reloads and nothing has changed, but AFTER the first time, it works fine...
my login.php handles either a) the post request, or b) the login via url (for testing purposes) so a link to "user/login.php?username=facebook&method=get" would be sent to the code below and set the user to logged in with the name facebook..
<?php
session_start();
$method = $_GET['method'];
if($method == "get") $_SESSION['username'] = $_GET['username'];
else $_SESSION['username'] = $_POST['username'];
header('Location: http://www.imggroups.com');
?>
Im not sure if this matters, but, on the index page, I check to see if the user is logged in by doing this. starting session obviously, then doing. if(isset($_SESSION['username'])) echo whatever i need for logged in.. else echo whatever for not logged in.....
The issue is that you are redirecting the user to a new page, but the old page has not finished closing, so the session is not yet saved.
In order to fix this I usually setup an interum page which redirects to the correct page.
Alternatively you might be able to use session_write_close() (http://www.php.net/manual/en/function.session-write-close.php) before using the header redirect
The fact of the matter is, it is setting the session, BUT it's redirecting you to a different domain that the session isn't allowed on. If you access the website without the 'www.' in front then get redirected to the www version afterwards, then it's going to say your session doesn't exist. Use the following:
session_set_cookie_params(0, '/', ".imggroups.com");
Put it before your session_start() and it will work for both www and non-www versions of your site.
If that is the total of the login.php, I believe there is easier ways to do that:
If it does not matter whether the username actually comes in via _GET or _POST, then use _REQUEST as it encapsulates both.
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_REQUEST['username'];
}
If it does matter, you don't have to trust or use an external parameter, just look at what's there:
if( isset($_POST['username'] ) {
$_SESSION['username'] = $_POST['username'];
} else if( isset($_GET['username'] ) {
$_SESSION['username'] = $_GET['username'];
} else {
// whinge
}
I've not run into that issue with PHP before, but you can also do a session_write_close(); to force it to write out the session before it redirects to the other page.
I also had this same issue if i open new window after logout in new tab or browser and try to log in login page stuck at loading i can see that session has been started because if i refresh on same stuck window i logged in to my dashboard.
But it was resolved later by redirecting it right:
Before
login.php (after ajax successful) --> index.php (if logged in) --> dashboard.php
After
login.php (after ajax successful) --> dashboard.php
hope it saves anybody's time & effort because i suffered alot!

Categories