使用AJAX / jQuery设置$ _SESSION | PHP会话不起作用?

时间:2011-12-13 21:42:38

标签: php jquery ajax

我正在为我的网站编写一个登录脚本。我已经编写了登录脚本,并且通过jQuery通过AJAX调用将表单绑定到它。

这是表单调用的php:

<?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"));
?>

但如果我console.log(result.session)我得到[],这让我觉得通过ajax设置会话变量是不可行的,或者会话本身不能正常工作。

我从这段代码中没有错误。

有人能指出我正确的方向吗?

我认为我无法访问php.ini,但我记得很久以前你必须将会话设置为在某个文件中运行,但对于我的生活我找不到一个例子

4 个答案:

答案 0 :(得分:5)

确保脚本开头有session_start()。如果在之前发送任何通知或任何内容,您将进入session_start(),那么您将收到如下错误:

  

警告:session_start():无法发送会话cookie - 已经发送的标头(输出始于......

此外,您的脚本对SQL注入开放。确保您正确地转义用户名和密码! 注意:最好的办法是使用prepared statements

答案 1 :(得分:1)

php脚本的一些提示:

  • 确保您启动会话作为php标记之后的第一个代码行,

    在session_start();
    //其他代码来到这里

注意:您还可以使用 session_id()

检查您的会话是否已启动
  • 首先分别测试Ajax调用的php脚本(将一些有效的$ _POST数据作为代码输入),并确保在返回json字符串之前没有回显任何内容并且没有得到警告(将被视为喜欢屏幕输出),

  • 您可能还会声明正确的标题,因为它们在此处缺失:

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

  • 不要忘记阅读请求答案的javascript回调: - )

答案 2 :(得分:0)

我已经离开PHP一段时间了,所以我可能会从我的基础谈起,但我认为你需要使用session_start()session_write_close()

在对$ _SESSION数组执行任何操作之前,应该调用session_start()。完成$ _SESSION的修改后,您应该调用session_write_close()

有关详细信息,请参阅http://www.php.net/manual/en/book.session.php

如果您的托管服务提供商尚未完成修改,您可能还需要修改php.ini。见http://www.php.net/manual/en/session.configuration.php

希望这有帮助。

答案 3 :(得分:0)

亲爱的@StephenRios特别感谢您的回答,我确实在代码中应用了上述设置,但实际上问题是关于CORS跨源资源共享,我遇到了这个问题并问了一个问题亲爱的@StephenRios特别感谢为了你的答案,我确实在代码中应用了上述设置,但实际上问题是关于CORS跨源资源共享,我遇到了这个问题并在stackoverflow中问了一个问题并且说我的朋友Milano Fili可以解决问题,

我在angularJS中使用了一个设置:

$httpProvider.defaults.withCredentials = true;

以及我的网络服务器中的设置(此处为apache)

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

非常感谢您的回复,我只是在这里分享了我的案例,因为我在谷歌上搜索超过3天,我希望,这可能有所帮助。