0

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

3
  • Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information. Commented Nov 4, 2012 at 8:30
  • Thanks, i accidentally removed md5 function to crypt it when posting the code. I'm already thinking about changing the login process using the new ways, but anyway i'm still going crazy for this annoying bug :) Commented Nov 4, 2012 at 8:33
  • I guess there is something wrong in config.php. could you post the source code here? Commented Nov 4, 2012 at 8:44

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for your help. Unfortunately this still happen. I now explain in words: User log in and it is redirected to dashboard and it show the error (While debugging $_SESSION var is 100% empty, no old session on it!). If he come back (and sometime if he just refresh) it will fix and "load" $_SESSION variables correctly. Still going crazy :)
0

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!

1 Comment

I published Config.php :) it always start session cause it's the first file included.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.