PHP $_SESSION variable not working first time - php

$_SESSION['isloggedin'] doesn't seem to be working on first load.
This only happens on server, not on localhost.
session_start() is at the top of each page.
initialized to: $_SESSION['isloggedin'] = false;
When user logs in $_SESSION['isloggedin'] = true;
When user logs out $_SESSION['isloggedin'] = false;
on home.php:
if (!$_SESSION['isloggedin']) {
die(header("Location: login.php"));
}
on login.php:
if ($_SESSION['isloggedin']) {
die(header("Location: home.php"));
}
When you login and sent to the home page $_SESSION['isloggedin'] doesn't seem to be true so it redirects to login.php. But since it is true it redirects to Home.php causing a redirect loop.
when a redirect loop error pops up, I refresh and am taken to the right page. Sometimes the page self refreshes and takes me to the correct page, still showing redirect error before.
Why isn't $_SESSION variable working properly on server? The correct value doesn't seem to register the first time on every page, every site link.
EDIT:
everything works as expected on localhost just not on the online server.
when login is clicked and everything passes the class login function is called:
class users {
$_SESSION['isLoggedIn'] = false;
function __construct() {
if (session_id() == "") {
session_start();
}
if (isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] == true) {
if (session_id() == '') {
session_start();
}
}
}
function login($user,$password) {
if (session_id() == "") {
session_start();
}
$_SESSION['isLoggedIn'] = false;
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if ($mysqli->connect_errno) {
return false;
}
$user = $mysqli->real_escape_string($user);
$password = $mysqli->real_escape_string($password);
$query = "SELECT * from users WHERE email=$user";
if (!$result = $mysqli->query($query)) {
return false;
}
$row = $result->fetch_assoc();
$db_pass = $row['password'];
if (crypt($password,$db_pass) != $db_pass) {
return false;
}
$_SESSION['isLoggedIn'] = true;
if (session_id() == '') {
session_start();
}
return true;
}
}

Try changing your code to something like this
if (!isset($_SESSION['isloggedin'])) {
header("Location: login.php");
} else {
header("Location: home.php");
}

I was using AWS Elastic Beanstalk to run this web app. I didn't think this matter but apparently it did. It turns out that sessions don't work the same as they do on localhost since you are dividing your servers. I needed to enable sticky session within the load balancer.

Related

PHP Session Works Slowly

I've started to learn PHP Sessions recently.That really helped me to do the login properly.
I should give the link to you first: mk-appform.net16.net/login.php(feel free to use as you want,This is a testing.Im able to change the pass as soon as it gets fixed)
Username:admin
Password:1234
Please test it
The problem is,When you're not logged in and type mk-appform.net16.net/advsearch.php directly in the adress bar,The content of the page that I require login beforehand is visible for a second.Then it redirects to login page.But you know,I would not want this to be shown in any way.It should require login eventually.
Here are the PHP codes of login.php
<?php
if (isset($_POST['submit']))
{
if(isset($_POST['user']) && isset($_POST['password']))
{
$user = $_POST['user'];
$password = $_POST['password'];
if(empty($user) || empty($password))
{
echo 'Please fill the form';
}
else
{
if($user == 'admin' && $password == '1234')
{ // check the infos
session_start();
$_SESSION['user'] = 'admin';
$_SESSION['password'] = '1234';
echo 'Login Succeeded.Now redirecting to panel...';
header("refresh:2; url=advsearch.php");
}
else
{
echo 'Invalid Username or Password';
}
}
}
else
{
echo 'Please use the form';
}
}
?>
And ,the code of the content I show after successfully logging in(advsearch.php)
<?php
session_start();
if(isset($_SESSION['user']) && isset($_SESSION['password']))
{
if($_SESSION['user'] == 'admin' && $_SESSION['password'] == '1234')
{
header("url=advsearch.php");
}
else
{
session_destroy();
echo 'Redirecting..';
}
}
else
{
header("refresh:0; url=login.php");
}
?>
header redirects aren't instantaneous. It takes a few moments for the browser to start shutting down the connection and initiate the new one. That means any content you output on the page after you output the location header can still be viewed. You have to abort your script after outputting the header. e.g.
<?php
if (need to redirect) {
header('Location: login.php');
echo 'redirecting to login page, please wait ...';
exit(); // you need this
}
... regular page contents ...
In short, if you don't want something visible to the user, then DON'T output it in the first place. Don't depend on everything working properly (or even fast). They rarely do.

cookies and sessions are not being saved

my site is working (sort off). When i check if there sessions are there, they echo out a message which works BUT when i check session storage in chrome, the sessions are not coming up, which is strange. I have also tried to set a cookie but that is not coming up either. So what am i doing wrong. So the sessions are working but not getting stored, and the cookies are not getting stored either
this is part of login class
public function __construct(DB $pdo)
{
$this->pdo = $pdo->pdo;
if(isset($_GET['logout'])){
$_SESSION = array();
session_destroy();
}
}
public function checklogin()
{
if(isset($_SESSION['user_sess']) && $_SESSION['logged_in'] === true){
return true;
} else {
return false;
}
}
public function loginwithdata($email, $password)
{
$query = $this->pdo->prepare('SELECT * FROM `users` WHERE `email` = ?');
$query->bindValue(1, $email);
try{
$query->execute();
$data = $query->fetch();
$salt = $data['salt'];
$user_key = $data['user_key'];
$hashed_pass = sha1(md5($salt.$password));
if($this->verify($hashed_pass, $email) === true){
$_SESSION['user_sess'] = $user_key;
$_SESSION['logged_in'] = true;
setcookie('key', '12345678910', 1209600, '/');
return true;
} else {
return false;
}
} catch(PDOException $e) {
die($e->getMessage());
}
}
here is the ajax_login.php
require '../core/init.php';
if(isset($_POST))
{
$email = $_POST['email'];
$password = $_POST['password'];
if(!empty($email) && (!empty($password))){
$try = $login->loginwithdata($email, $password);
if($try){
//login successful
echo 'success';
} else {
echo 'login failed';
}
}
}
and on my index page i have
require_once 'core/init.php';
if($login->checklogin() === true){
echo "you are logged in";
} else if ($login->checklogin() === false) {
echo "you are not logged in";
}
and my init file
session_start();
error_reporting(E_ALL);
date_default_timezone_set('Europe/London');
require_once 'classes/DB.php';
require_once 'classes/Upload.php';
require_once 'classes/Login.php';
require_once 'classes/Register.php';
require_once 'classes/Site.php';
require_once 'classes/Admin.php';
require_once 'sinitize.php';
$pdo = new DB;
$upload = new Upload($pdo);
$login = new Login($pdo);
$register = new Register($pdo);
Your code looks good so far.
But wait.. dude.. Sessions generally get stored in a COOKIE (as ID). SESSION STORAGE and WEB STORAGE in chrome is something completely different and is sorta part of HTML5 rather than PHP Sessions.
You say you get the proper echoes so there is really nothing wrong with your session.
If you open the developers console and in networking tab you see the cookie sent, it's everything perfect.
If you are having problems with the session cookie itself,
please provide and check the session configuration variables from php.ini:
From console:
php -i | grep session
or use phpinfo(); in a web served script.
session.use_cookies should be On
See: http://www.php.net/manual/de/ini.list.php
Some browsers, if path is set, wants the domain too:
setcookie ( $name, $value, $expire, $path, $domain);
About $expire
It's the "absolute" time in seconds since Epoc when the cookie expire, so expire within an hour should be:
$expire = time()+3600;
see also:
http://www.php.net/setcookie

Session variable for login not passing to redirected page on first attempt

hi I have a login system for my admin section that i have a problem with, the problem is that the first time the user attempts to login, the $_SESSION isn't passed to the target page,
on the second attempt it works fine, this is what is called on the login page
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
header("location: ambassadorUpdate.php");
die;
} else return "Please enter a correct username and password";
}
i've checked the code when i don't then send to ambassadorUpdate and the SESSION is set however if i use the header to redirect to page then the first time the SESSION is not
there is a session_start on both pages,
the code runs fine when all the pages where in the same folder, however i am getting this problem when i have organised them in a separate admin folder however all of the files are included correctly,
any ideas greatly appreciated many thanks
Try to modify:
$membership = new Membership();
if($_POST && !empty($_POST['username']) && !empty($_POST['pwd'])) {
$response = $membership->validate_User($_POST['username'], $_POST['pwd']);
}
if ($response == true){
header("location: ambassadorUpdate.php");
} else echo "Please enter a correct username and password";
in the class memebership
function validate_user($un, $pwd) {
$ensure_credentials = $this->verify_Username_and_Pass($un, $pwd);
if($ensure_credentials) {
echo 'workied';
$_SESSION['status'] = 'authorized';
$_SESSION['id'] = $ensure_credentials;
echo $_SESSION['status'] . $_SESSION['id'];
return = true;
} else return false;
}
I can't create an comment, so i write an answer.
Have you check session_start() in ambassadorUpdate.php. Does your browser accept cookies?
If not, it is usefull to use "location: ambassadorUpdate.php".?SID or you can use session_name()=session_id() instead of SID
Hope this helps.

PHP and jQuery AJAX $_SESSION Bug

I spent many days to fix this problem and i can't find a solution.
After i login using my ajax form + php backend, the page where user is redirected show the "Missing session" message and if i try dumping $_SESSION it looks like empty. Then, if i go back and i do the same login it will work correctly. This happen in different browser (usually when they have cookie and cache clear) and in different hosting providers.
This is my ajax code:
$(document).ready(function(){
$('#loginbtn').click(function(){
if($('#username').val() == "" || $('#password').val() == ""){
return false;
}
else
{
$.ajax
({
type: 'POST',
url: 'ajax_login.php',
cache: false,
dataType: 'json',
data:
{
username: $('#username').val(),
password: $('#password').val()
},
success:function(data)
{
if(data.error === true){
alert("Failed to login: "+data.message)
}
else
{
setTimeout(function()
{
window.location = 'http://www.mywebsite.com/dashboard.php';
},2000);
}
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("An error occured!");
}
});
return false;
}
});
});
This is the PHP Login Backend:
<?php
include "config.php"; // start session and connect to mysql db, also contain functions sanitize(), getip()
$username = sanitize(htmlspecialchars($_POST['username'],ENT_QUOTES));
$pass = sanitize($_POST['password']);
// FUNCTION TO LOGIN
$sql = mysql_query("SELECT * FROM members WHERE username = '$username' AND password = '$pass'");
$array = mysql_fetch_array($sql);
if(mysql_num_rows($sql) === 0){
$message['error'] = true;
$message['message'] = "Wrong username or password.";
echo json_encode($message);
exit;
}
$_SESSION['username'] = ucwords(strtolower($username));
$_SESSION['points'] = $array['points'];
$_SESSION['ip'] = getip();
$_SESSION['welcome'] = true;
$message['error'] = false;
$message['message'] = "Completato.";
echo json_encode($message);
exit;
And finally this is dashboard.php check session code:
<?php
include "config.php";
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
Edit: This is what's inside config.php
<?
session_start();
date_default_timezone_set("Europe/Rome");
$hostname = ""; //hostname
$data_username = "dbxxxxxxxx"; //database username
$data_password = "xxxxx"; //database password
$data_basename = "dbxxxxxxx"; //database name
$conn = mysql_connect("".$hostname."","".$data_username."","".$data_password."");
mysql_select_db("".$data_basename."") or die(mysql_error());
function sanitize($text) { // funzione che pulisce le stringe per prevenire exploit;
if(get_magic_quotes_gpc() == 0) {
$text = addslashes($text);
}
$text = htmlentities($text);
$text = strip_tags($text);
$escape = mysql_real_escape_string($text);
$arraydangerous = array('SELECT *', 'LOAD_FILE', 'DELETE', 'TRUNCATE', '\' OR', '<javascript>', 'src=', '<?', '?>', 'document.cookie', 'http://', 'www.');
$text = str_replace($arraydangerous, "", $text);
return $text;
}
function getip()
{
return filtra($_SERVER['HTTP_CF_CONNECTING_IP']); // I use CloudFlare ,so i must use this way :)
}
How can i fix this? Thanks
In config.php add this lines after session_start();.
session_start();
// reset the session, if not logged-in
if (empty($_SESSION['username'])) {
$_SESSION['username'] = null;
$_SESSION['points'] = null;
$_SESSION['ip'] = null;
$_SESSION['welcome'] = null;
}
Also I guess it's better you changing dashboard.php to something like this:
<?php
include "config.php";
if($_SESSION['username'] == "") {
header("Location: index.php?nosession");
exit;
}
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
?>
I think your problem is the old sessions that you have on your server, while testing your code. For example you are trying to log in, you add the values to the session but for any reason you receiving some errors, and you see that you're not logged in. You forgot that you already add some data to the session, you refresh the dashboard.php and you see that hey, it seems that you're already logged in. Then you might think that your code is crazy, working randomly or any other irrelevant reason. (a few years ago, I had a code that was working when it was raining on the day, and didn't work when it wasn't rainy. Fortunately, I solved that problem in 2 days, before getting crazy!)
You might also clean all the sessions stored on your server, to be sure you have a clean test, while you're changing the code.
I hope these gonna helps somehow.
I'm not sure if this is the case or what (since I don't know what's inside config.php), but it seems to me that you forgot to start the session before you use it in your "PHP Login Backend" file!

"Dynamics" sessions

We have a login form that is processed by php and ajax. The ajax sends a request to the php page with the username and password to be logged in. It gets a response and if it's correct and working info, it logs them in:
The php page that takes requests has this code:
echo (checkLogin($_POST['user'], $_POST['pass']) ? 'true' : 'false');
if(checkLogin($_POST['user'], $_POST['pass']) == true)
logIn($_POST['user'], $_POST['pass']);
The functions used in that statement:
function logIn($user, $pass)
{
$_SESSION['sid'] = md5(md5($user) . md5($pass));
$_SESSION['username'] = $user;
$_SESSION['password'] = $pass;
}
function checkLogin($user, $pass)
{
$user = strtolower($user);
$pass = strtolower($pass);
$res = mysql_query("SELECT * FROM users WHERE username='".$user."'");
if(mysql_num_rows($res) == 1)
{
$data = mysql_fetch_assoc($res);
if($data['pass'] == aCrypt($pass))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Now, it seems that the session is started and only able to be seen AFTER the user reloads the page. We need it to start the session right on the page...would we need to refresh the entire page with ajax? I don't really know where to go from here.
You probably want to use the Post-Redirect-Get pattern; after the user is successfully authenticated, use a redirect to send him to a new page.
As I noted above, please look into fixing the SQL injection and session fixation vulnerabilities in your code as well.

Categories