StephenRios
StephenRios

Reputation: 2242

Setting $_SESSION with AJAX/jQuery | PHP Sessions Not Working?

I am writing a login script for my website. I've written the login script, and I have the form tied to it via an AJAX call through jQuery.

Here is the php the form is calling:

<?PHP   
    # Make sure form data was passed to the script
    IF (isset($_POST) && isset($_POST['username']) && isset($_POST['password'])){
        # Connect to the database
        REQUIRE('../../../../my_db.php');

        # Define variables
        $given_username = $_POST['username'];
        $given_password = $_POST['password'];
        $hashed_password = md5($given_password);
        $matched_username = "";
        $matched_password = "";


        # See if there is matching info in the database
        $sql = 'SELECT username, pass FROM users WHERE username="'.$given_username.'" AND pass = "'.$hashed_password.'"';
        $result = mysql_query($sql);
        WHILE($row = mysql_fetch_assoc($result)){
            $matched_username = $row['username'];
            $matched_password = $row['pass'];
        };


        # If there was a match
        IF ($matched_username != "" && $matched_password != ""){

            # Double check the values match
            IF ($given_username == $matched_username && $hashed_password == $matched_password){

                # If there is only one result returned
                $session_sql = 'SELECT * FROM users WHERE username="'.$matched_username.'" AND pass = "'.$matched_password.'"';
                $session_result = mysql_query($session_sql);
                IF(count(mysql_fetch_assoc($session_result)) != 0  &&  count(mysql_fetch_assoc($session_result)) < 2){

                    # If they do, start a session
                    if(!isset($_SESSION)) {
                     session_start();
                     session_regenerate_id();
                    };

                    # Set our session values
                    WHILE($session_row = mysql_fetch_assoc($session_result)){
                        $_SESSION['id'] = $session_row['id'];
                        $_SESSION['last_login'] = $session_row['last_login'];
                        $_SESSION['username'] = $session_row['username'];
                        $_SESSION['signup_date'] = $session_row['signup_date']; 
                    };

                    # Set users last login date and time to this login
                    $update_sql = 'UPDATE users SET last_login = NOW WHERE username="'.$matched_username.'" AND pass = "'.$matched_password.'"';
                    $update = mysql_query($update_sql);

                    echo json_encode(array("success"=>"user logged in", "session"=>$_SESSION));
                }ELSE 
                    echo json_encode(array("error"=>"More than one user with the same information.  What did you do?!"));
            }ELSE
                echo json_encode(array("error"=>"invalid login provided"));
        }ELSE
            echo json_encode(array("error"=>"invalid login provided"));
    }ELSE
        echo json_encode(array("error"=>"you must supply a username and password"));
?>

But if I do console.log(result.session) I get [], which makes me think that either setting session variables through ajax isn't viable, or the session itself isn't working properly.

I get no errors from this code.

Can somebody point me in the right direction?

I don't think I have access to php.ini, but I remember from a long time ago that you had to set sessions to run in a file somewhere, but for the life of me I can't find an example.

Upvotes: 4

Views: 11261

Answers (4)

Ebrahim
Ebrahim

Reputation: 1818

Dear @StephenRios especially thanks for your answers, I did apply the mentioned settings in the code, But actually the problem was about CORS Cross-Origin Resource Sharing, I was stuck with this issue and asked a question Dear @StephenRios especially thanks for your answers, I did apply the mentioned settings in the code, But actually the problem was about CORS Cross-Origin Resource Sharing, I was stuck with this issue and asked a question in stackoverflow and speaking my friend Milano Fili could solve the problem,

I used a setting in angularJS:

$httpProvider.defaults.withCredentials = true;

and also a setting in my web server (here apache)

Header add Access-Control-Allow-Credentials "true"

very appreciated for your replies, I just shared my case here because I was googling this more than 3 days, I hope, it could help.

Upvotes: 1

hornetbzz
hornetbzz

Reputation: 9367

Some hints for your php script :

  • Make sure you started a session as the first code line after the php tag,

    session_start();
    // other code comes here

Note: you can also check that your session is started using session_id()

  • First test separately the php script called by Ajax (put some valid $_POST data as code entry) and make sure you do not echo anything before your return json strings and you do not get warnings (that will be considered like screen outputs),

  • you might also declare the right headers as they look missing here :

    header('Content-type: application/json');

  • Do not forget the javascript callback to read the request answer :-)

Upvotes: 1

Yes Barry
Yes Barry

Reputation: 9876

Make sure you have session_start() at the beginning of your script. If any notices or anything is thrown before you get to session_start() then you'll get an error like this:

Warning: session_start(): Cannot send session cookie - headers already sent by (output started at...

Also, your script is open to SQL injection. Make sure you properly escape the username and password! Note: your best bet is to use prepared statements.

Upvotes: 5

Misha Gale
Misha Gale

Reputation: 97

I've been away from PHP for a while, so I might be talking from my fundament, but I think you need to be using session_start() and session_write_close().

You should call session_start() before you do anything to the $_SESSION array. Once you have finished modifying $_SESSION you should call session_write_close()

For more details, see http://www.php.net/manual/en/book.session.php

You may also need to modify php.ini, if your hosting provider hasn't done it already. See http://www.php.net/manual/en/session.configuration.php

Hope this helps.

Upvotes: 0

Related Questions