Session problem during refresh - php

When i refresh my flex application, the page does not hold its state and gets back to login page. I am not sure why this occurs, Here is my peiece of code handling session.
public function doLogin($username,$password) {
include("connection.php");
session_start();
session_register("session");
$query = "SELECT *
FROM users
WHERE username = '".mysql_escape_string($username)."'
AND password = '".mysql_escape_string($password)."'";
$result = mysql_fetch_array(mysql_query($query));
if(!$result) {
session_unset();
return 'no';
}
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
public function Logout() {
session_start();
session_register("session");
session_unset();
session_destroy();
return 'logout';
}
Should i do something on my Flex pane which loads after a successful login.

your problem is here
else
{
$session['id']=session_id();
$session['username']=$username;
return 'yes';
}
}
$session is not defined... if you want to store something in the session array use $_SESSION

After successful login redirect back to some other page.
For example
if(doLogin($user,$pass) == 'yes')
{
Header("Location: index.php");
exit;
}

By refresh do you mean reload the page (F5). If so then that is the reason! A reload/refresh will reinitialise everything. So whatever is your starting state (login) will be shown when you reload/refresh.
If you wish to maintain the apps state then every time the state changes you would have to save its details to a DB then when the user hits the starting page reload their session.
If the browser gets refreshed/reloaded (or crashes etc) then you have no means of getting the app to logout the user, so you'd have to revert to the last know state when the login page gets hit. This would of course have major security issues if the user didn't log of properly.

Are you maintaining the session id in your flex application, and sending it along with new requests?
Can you test & confirm that the same session id is being returned from your PHP scripts on each request inside Flex?
Are you persisting the session id in a cookie outside of your flex application? If not, you will lose your session id on page refresh. You'll need to store in local storage or in a cookie, and access this when your flex application starts.

Related

Session not destroying when logging out of online website but works with offline website

I just finished creating a website that includes a login page. When the user attempts to log in, I check the username and password against the database. If they both match, I start a session and set the session variables 'id' and 'uid', like so:
$sql = "SELECT * FROM users WHERE uidUsers = ? OR emailUsers = ?";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ../login.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if ($pwdCheck == false) {
header("Location: ../login.php?error=wrongpwd&mail=".$mailuid);
exit();
}
elseif($pwdCheck == true) {
session_start();
$_SESSION['id'] = $row['idUsers'];
$_SESSION['uid'] = $row['uidUsers'];
header("Location: ../login.php?login=success");
exit();
}
else {
header("Location: ../login.php?error=wrongpwd");
exit();
}
}
else {
header("Location: ../login.php?error=nouser&mail=".$mailuid);
exit();
}
}
In my header.php file, which is linked within every php page using include 'header.php';, I have php code that displays either log in/sign up buttons (if $_SESSION['id'] is not set) or a log out button (if $_SESSION['id'] is set). I also started a session in the header.php page. This is what the code of header.php looks like:
session_start();
if (isset($_SESSION['id'])) {
echo
"<div id='logout-form'>
<form action='includes/logout.inc.php' method='post'>
<button type='submit' name='logout-submit'>Log Out</button>
</form>
</div>";
}
else {
echo
"<div id='header-form'>
<form action='includes/login.inc.php' method='post'>
<button type='submit' name='login-button-header'>Log In</button>
</form>
<button id='signup-button'><a href='signup.php' class='header-signup'>Sign Up</a></button>
</div>";
}
if (isset($_SESSION['id'])) {
echo '<p class="greeting">Hello, <span class="greetingName">' . $_SESSION['uid'] . '</span></p>';
}
date_default_timezone_set("America/Los_Angeles");
Using xampp, I am connected to an apache server offline. When clicking through my site, the sessions work for every page; if I log in, it registers that I've logged in on every page I go to, as it should. However, when I posted my website a few days ago, it had trouble knowing if I was logged in or out. My website URL is writingboxco.com if you would like to see what I'm about to talk about. When I log in, it seems to know that I am logged in on every web page; I know this because it provides the message "Hello, [username]" on every page, which only happens when $_SESSION['id'] is set. However, when I click "Log Out" and go back to the home page, it still thinks that I'm logged on (because I probably am, but I don't know why). When the "Log Out" button is clicked, the script "logout.inc.php" runs. In this file, I unset and destroy the session variables, like so:
session_start();
session_unset();
session_destroy();
$_SESSION = [];
header("Location: ../login.php");
Additionally, I only stay logged in on some pages of the website. Some of them register that I've logged out, while other don't.
I'm not sure why I stay logged in after clicking the "Log Out" button, which should destroy the session variables. When my site is used offline, it works perfectly fine; when I log out, every page realizes it. However, when online, it doesn't work for every page. It only works for some (some pages stay logged in and some pages correctly log out). Additionally, when I try to log in with an alternate account, it signs me in, but on certain pages, the message "Hello [username]" still displays the username of the account I just logged out of instead of the account I just logged into. Any ideas on what the problem could be? Is it a problem with the failure to destroy the session variables? Could it be other code I should be looking at? Thanks.
UPDATE:
I found that there is an error message stating [28-Jan-2020 00:02:56 UTC] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home1/writipe3/public_html/searchUsers.php:1) in /home1/writipe3/public_html/header.php on line 5
on the error_log file. Any ideas why this would be happening?
When you're destroying a session in PHP you're not actually deleting it. You're merely marking it for garbage collection. The physical deletion happens later. So in order to ensure the session is actually destroyed you must also delete the session cookie, which propagate the session id.
If you look at Example #1 of the session_destory() documentation you'd see some sample code of how to go about doing this:
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
Why is this behavior variable across platforms?
The reason you may see differences in how this atually works out in practice is because different platforms can use different methods of garbage collection for cleaning up session data. For example, on most Windows systems this might actually happen instantly. Some Debian-based (Ubuntu) systems are known to use an asynchronous GC method that happens outside of PHP.
PHP, by default, implements this via a probablistic algorithm wherein each request made to PHP will, within a given probability (usually about 1% of the time) will trigger the GC cycle. So the clean up is non-deterministic in almost all cases.

PHP- How can I restrict access to a page?

I have multiple pages that needs to be protected depending on the user privilege. I have a php to check the current session variable upon page load.
page being tested; the php code is placed above the !DOCTYPE. this code is suppose to check for unlogged in customers. if not logged in or no session variable set redirect to error page otherwise do nothing and load page normally
<?php
if (!isset($_SESSION["username"])){
header("location: error.php");
}
?>
my session variables are only set after logging in, after logging in the user is redirected to the page referred to above:
if (mysqli_num_rows($results6) < 1) { //$results6 is a query to check if the user exits in the users database
$logInMsg = "invalid log in";
} else {
session_start();
$_SESSION["username"] = $uName; //$uName is a user input user name
header("location: pageabove.php");
}
the problem is that even after logging in I still get redirected to the error page
That would be because you haven't started the session yet. You need to specify a session start on each page that you intend to use sessions in (Read more about session_start()):
<?php
session_start(); // start session
// do check
if (!isset($_SESSION["username"])) {
header("location: error.php");
exit; // prevent further execution, should there be more code that follows
}
This is for everything. On your login page and all. Anywhere you want to harness the sessions, you need to start it, otherwise it's "lost in the wind".

PHP Cookies not being loaded when coming from a clicked link

I'm working on a website that is keeping a user session token in $_SESSION. When I type the URL directly, I can load the cookies just fine, but when I click on a page that loads the cookie through PHP, it can't find the cookie. Is there any way to get around this?
Here's the code for saving the cookie
setcookie("tpl_token", $token, time()+365*24*60*60, "/");
And for retrieving
if(isset($_COOKIE['tpl_token'])){
$token = $_COOKIE['tpl_token'];
} else {
echo "Cookie not set";
}
It is returning that cookie is not set.
In order to create a session in PHP, use the session_start() function. PHP handles sessions internally for you, so you do not have to do any dirty work.
Example:
session_name("tpl_token");
session_start(); //sends session cookie with name "tpl_token"
//create session variable.
$_SESSION["logged_in"] = true;
if(isset($_SESSION["logged_in"])){
//stuff to do if user is logged in already
} else {
//stuff to do if user is not logged in.
}
//Destroy Session/Logout;
session_unset();
session_destroy();
If you are try create session cookies, there is no need for the $_COOKIE[] function

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 Session (Login page and userpage)

I need to create a session on index page
if user already login in, it will header to member page.
if user destroy session, it will stay at index(login page)
what i did is
if(session_start){
header("location:member.php") or die();
}
if(isset($_POST['email']) && isset($_POST['password'])){
$email=strtolower($_POST['email']);
$password=md5($_POST['password']);
if($email && $password){
$connect=mysql_connect("localhost", "root", "");
$database=mysql_select_db("phplogin", $connect);
$SQL=mysql_query("SELECT * FROM users WHERE email='$email'");
$numrows=mysql_num_rows($SQL);
if($numrows!=0){
while($result=mysql_fetch_assoc($SQL)){
$db_email=$result['email'];
$db_password=$result['password'];
$db_firstname=$result['firstname'];
$db_lastname=$result['lastname'];
}
}
else{
die("Can't find the user");
}
if($email==$db_email && $password==$db_password){
session_start();
$_SESSION['firstname']=$db_firstname;
$_SESSION['lastname']=$db_lastname;
header("location:member.php");
}
else{
die("wrong username or password");
}
}
else{die("Please enter email or password");}
}
This works when user haven't destroy session, but when user destroy session
it didn't stay at index page
I need something like facebook, yet I don't know how facebook can share same the domain name on login page and user page.
so everytime i type facebook.com i will go to my user page, if i logout, it will become login page
You have used if(session_start). session_start() is a function. And it is used on each and every page. So it will redirect you everytime.
Another thing, you need to session_start() on the page you are storing the session and the page you are getting session values.
Instead of:
if(session_start){
header("location:member.php") or die();
}
Use:
session_start();
if(isset($_SESSION['firstname']) && isset($_SESSION['lastname'])){
header('location:member.php');
}
//and REMOVE session_start(); from where you have written.
How about on top of your page
if(!isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])){
header("location:index.php") or die();
}
First of all; only checking if a session exists isn't enough if you want to check if your user is logged in (the session could exist all the same, even if the user isn't logged in). So you should write a is_logged_in() function (or something like that) first to properly check the logged in status.
The reason why your user is always redirected is because the function session_start() returns true if a session is started succesfully; if the session is destroyed, it just starts a new one. So basically it will return true pretty much always, if everything works correctly (like user has not turned cookies off etc.).
If you have written that function it's actually quite simple. Let's pretend you have two files: home.php and member.php. The first one is your homepage (with a "Hello visitor!" message and the login form), the second is the member page. If both files are 'standalone' scripts you can indeed header the user to the specific page (header('Location: home.php'); if user should login first, header('Location: member.php'); if user is already logged in).
But! If you want to 'cloak' the pages (pretty much like facebook does it), you can just include the files in your index.php. Do something like this:
if(is_logged_in()) {
require_once('member.php'); // present member profile page
} else {
require_once('home.php'); // present login page
}
In your index.php you can set a constant (see also the php manual about constants) to be sure the files can only be included from within index.php:
--- index.php:
define('VALID_INCLUDE', true);
// the rest of your code
--- home.php & member.php:
if(!defined('VALID_INCLUDE')) die('You should not request this page directly');
But please note that if you want to write applications like this, a framework could help you a lot; it covers a lot if this kind of problems and makes coding a lot faster (most frameworks come with a authentication modules of some sort, and allow you to use 'views' to present your user with the proper pages, like I have done above with the require_once solution).

Categories