views:

244

answers:

3

I am trying to create a simple log in system that uses ajax but the problem I am having it wont set the $_SESSION.

login.js:

 $('#bt-login').click(function(){
        var login = $('#login').serialize();
        $.ajax({
            type: "POST",
            url: 'widgets/Login/loginFunction.php',
            data: login,
            cache: false,
            success: function(msg){alert(msg)}
        });
});

loginFunction.php:

 <?php
     include_once '../../dbConfig.php';
     include_once '../../config.php';

     session_start();

      $usr = mysql_escape_string($_POST['username']);
      $pass = mysql_escape_string($_POST['password']);
      $remember = intval($_POST['rememberMe']);

      $row = mysql_fetch_assoc(mysql_query("SELECT usr, id FROM members WHERE usr='".$usr."' AND pass='".md5($pass)."'"));

      if($row['usr']){
          $_SESSION['usr'] = $row['usr'];
          $_SESSION['id'] = $row['id'];
          $_SESSION['rememberMe'] = $remember;
          setcookie('DirtPileGames',$remember);
      }

 ?>

Now for some reason loginFunction.php is not setting the $_SESSION. I do a refresh and $_SESSION is blank.

Does anyone have any ideas why this wont work.

+1  A: 

Don't know the specific problem, because the session should be valid assuming you're not accidentally calling session_destroy() somewhere. Some advice for debugging - make sure the session_id() matches on the pages; if it doesn't something funny is going on. Could try explicitly calling session_write_close(). In addition set something in $_SESSION for the error case (when the user doesn't exist) to make sure its not a simple logic error. Also, don't use an md5 pretty please. Use some variant of sha, and salt it.

Edit: you mention session_name()

This call fixes the name of the session so you can refer to it on other pages. If you do a session_start() on another page without naming the session identically, it will spawn a new session with a new id.

Note from the php documentation: The session name is reset to the default value stored in session.name at request startup time. Thus, you need to call session_name() for every request (and before session_start() or session_register() are called).

Josh
I did the session_id and I am getting two different id's. The main part of the site I am getting 33a77eefa3a27732485fd86245661548 but the php file used for my ajax I am getting 7c54561b0fcb89765db0b9da4a2a83d3.
WAC0020
+2  A: 

Make sure you call session_start() every time you want to access or set session variables. It will be blank when you refresh a page unless you first call session_start().

RenderIn
A: 

Sessions are dependent on cookies, try an leave out the

setcookie('DirtPileGames',$remember);

See if this clears up the issue, a lot of problems depend on your php stack.

DCC