PHP会话ID无效

时间:2017-06-13 03:40:21

标签: php html facebook session

我是php的新手。我试图使用session来存储用户ID。但是,showSession.php在id部分中不打印任何内容。我错过了代码中的任何内容吗?谢谢!

loginfb.php用于访问数据库

    <?php
    session_start();
    //Load the database configuration file
    require("config.inc.php");

    //Convert JSON data into PHP variable
    $userData = json_decode($_POST['userData']);
    if(!empty($userData)){
        $oauth_provider = $_POST['oauth_provider'];
        //Check whether user data already exists in database
        $prevQuery = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
        try {
        $stmt   = $db->prepare($prevQuery);
        $result = $stmt->execute();
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }
        $rows = $stmt->fetchAll();
        if($rows){ 
            //Update user data if already exists
            $query = "UPDATE users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
            $update = $db->query($query);
            $_SESSION["id"] = $rows['id'];
        }else{
            //Insert user data
            $query = "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
            $insert = $db->query($query);
            $getSession = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
             try {
        $stmt1   = $db->prepare($getSession);
        $result1 = $stmt1->execute();
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }
        $rows1 = $stmt1->fetchAll();
        if($rows1){ 
            $_SESSION["id"] = $rows1['id'];
        }
        }

    }
    ?>

showSession.php用于打印会话ID。

    <?php
    session_start();
    echo session_id();
    $id=$_SESSION['id'];

    echo "Session id is " . $_SESSION["id"] . ".<br>";
    echo "Session id is " . $id . ".<br>";
    print_r($_SESSION);
    ?>

login.html是允许用户使用facebook帐户登录的用户界面。

    <!DOCTYPE html>
    <html>
    <style>
    form {
        border: 3px solid #f1f1f1;
    }

    input[type=text], input[type=password] {
        width: 100%;
        padding: 12px 20px;
        margin: 8px 0;
        display: inline-block;
        border: 1px solid #ccc;
        box-sizing: border-box;
    }

    button {
        background-color: #4CAF50;
        color: white;
        padding: 14px 20px;
        margin: 8px 0;
        border: none;
        cursor: pointer;
        width: 100%;
    }

    button:hover {
        opacity: 0.8;
    }

    .registerbtn {
        width: auto;
        padding: 10px 18px;
        background-color: #f44336;
    }

    .imgcontainer {
        text-align: center;
        margin: 24px 0 12px 0;
    }

    img.avatar {
        width: 40%;
        border-radius: 50%;
    }

    .container {
        padding: 16px;
    }

    span.psw {
        float: right;
        padding-top: 16px;
    }

    /* Change styles for span and cancel button on extra small screens */
    @media screen and (max-width: 300px) {
        span.psw {
           display: block;
           float: none;
        }
        .registerbtn {
           width: 100%;
        }
    }
    </style>
    <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

    <script>
    window.fbAsyncInit = function() {
        // FB JavaScript SDK configuration and setup
        FB.init({
          appId      : '1537121876329962', // FB App ID
          cookie     : true,  // enable cookies to allow the server to access the session
          xfbml      : true,  // parse social plugins on this page
          version    : 'v2.8' // use graph api version 2.8
        });

        FB.Event.subscribe('auth.login', function(){
        window.location.href = 'showSession.php';
    });

    FB.Event.subscribe('auth.logout', function(){
        window.location.href = 'login.html';
    });

        // Check whether the user already logged in
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                //display user data
                getFbUserData();
            }
        });
    };

    // Load the JavaScript SDK asynchronously
    (function(d, s, id) {
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return;
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));

    // Facebook login with JavaScript SDK
    function fbLogin() {
        FB.login(function (response) {
            if (response.authResponse) {
                // Get and display the user profile data
                getFbUserData();
            } else {
                document.getElementById('status').innerHTML = 'User cancelled login or did not fully authorize.';
            }
        }, {scope: 'email'});
    }

    // Fetch the user profile data from facebook
    function getFbUserData(){
        FB.api('/me', {locale: 'en_US', fields: 'id,first_name,last_name,email,link,gender,locale,picture'},
        function (response) {
            document.getElementById('fbLink').setAttribute("onclick","fbLogout()");
            document.getElementById('fbLink').innerHTML = 'Logout from Facebook';
            document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.first_name + '!';
            document.getElementById('userData').innerHTML = '<p><b>FB ID:</b> '+response.id+'</p><p><b>Name:</b> '+response.first_name+' '+response.last_name+'</p><p><b>Email:</b> '+response.email+'</p><p><b>Gender:</b> '+response.gender+'</p><p><b>Locale:</b> '+response.locale+'</p><p><b>Picture:</b> <img src="'+response.picture.data.url+'"/></p><p><b>FB Profile:</b> <a target="_blank" href="'+response.link+'">click to view profile</a></p>';

            // Save user data
            saveUserData(response);
        });
    }

    // Logout from facebook
    function fbLogout() {
        FB.logout(function() {
            document.getElementById('fbLink').setAttribute("onclick","fbLogin()");
            document.getElementById('fbLink').innerHTML = '<img src="fblogin.png"/>';
            document.getElementById('userData').innerHTML = '';
            document.getElementById('status').innerHTML = 'You have successfully logout from Facebook.';
        });
    }

    // Save user data to the database
    function saveUserData(userData){
        $.post('loginfb.php', {oauth_provider:'facebook',userData: JSON.stringify(userData)}, function(data){ return true; });
    }
    </script>
    <h2>Login Form</h2>

    <form action="loginUser.php" method="post">
      <div class="imgcontainer">
        <img src="img_avatar2.png" alt="Avatar" class="avatar">
      </div>

      <div class="container">
        <label><b>Username</b></label>
        <input type="text" placeholder="Enter Username" name="username" required>

        <label><b>Password</b></label>
        <input type="password" placeholder="Enter Password" name="password" required>

        <button type="submit">Login</button>
        <input type="checkbox" checked="checked"> Remember me
      </div>

      <div class="container" style="background-color:#f1f1f1">
        <button type="button" class="registerbtn" onclick="location.href='register.html'">Register</button>
        <span class="psw">Forgot <a href="#">password?</a></span>
      </div>
    </form>
    <!--
    <div
      class="fb-like"
      data-share="true"
      data-width="450"
      data-show-faces="true">
    </div>
    -->
    <!--
    <div id="status"></div>
    -->
    <!-- Facebook login or logout button -->
    <a href="javascript:void(0);" onclick="fbLogin()" id="fbLink"><img src="fblogin.png"/></a>
    <!--
    <div id="userData"></div>
    -->
    </body>
    </html>

2 个答案:

答案 0 :(得分:0)

可能是因为你的程序的这部分没有执行。

    $rows1 = $stmt1->fetchAll();
    if($rows1){ 
        $_SESSION["id"] = $row['id'];
    }

在此原因如果if条件未接近,则数据将不会存储在session中。尝试在上面的if condition中打印出一个字符串,看它是否正在执行。

答案 1 :(得分:0)

您可以尝试使用下面的代码,因为我可以看到一些变量命名问题。希望这会有所帮助

<?php
    session_start();
    //Load the database configuration file
    require("config.inc.php");

    //Convert JSON data into PHP variable
    $userData = json_decode($_POST['userData']);
    if(!empty($userData)){
        $oauth_provider = $_POST['oauth_provider'];
        //Check whether user data already exists in database
        $prevQuery = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
        try {
        $stmt   = $db->prepare($prevQuery);
        $result = $stmt->execute();
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }
        $rows = $stmt->fetchAll();
        if($rows){ 
            //Update user data if already exists
            $query = "UPDATE users SET first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', modified = '".date("Y-m-d H:i:s")."' WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
            $update = $db->query($query);
            $_SESSION["id"] = $rows['id']; //changed $row with $rows
        }else{
            //Insert user data
            $query = "INSERT INTO users SET oauth_provider = '".$oauth_provider."', oauth_uid = '".$userData->id."', first_name = '".$userData->first_name."', last_name = '".$userData->last_name."', email = '".$userData->email."', gender = '".$userData->gender."', locale = '".$userData->locale."', picture = '".$userData->picture->data->url."', link = '".$userData->link."', created = '".date("Y-m-d H:i:s")."', modified = '".date("Y-m-d H:i:s")."'";
            $insert = $db->query($query);
            $getSession = "SELECT * FROM users WHERE oauth_provider = '".$oauth_provider."' AND oauth_uid = '".$userData->id."'";
             try {
        $stmt1   = $db->prepare($getSession);
        $result1 = $stmt1->execute();
    }
    catch (PDOException $ex) {
        $response["success"] = 0;
        $response["message"] = "Database Error!";
        die(json_encode($response));
    }
        $rows1 = $stmt1->fetchAll();
        if($rows1){ 
            $_SESSION["id"] = $rows1['id']; //changed $row with $rows1
        }
        }

    }
    ?>