如何在php中使用会话变量?

时间:2017-04-04 10:58:41

标签: php json session post get

我已经构建了一些返回json响应的粗略休息api。一个api接受POST请求并用于登录用户,另一个接受GET请求并从数据库中读取用户的内容。

如果登录成功,则设置 $ _ SESSION [“uid”] 变量以检查GET响应是否来自同一用户。基本上,登录api从用户数据库返回存储在 $ _ SESSION [“uid”] 变量中的用户标识。 GET请求读取内容,将此userid作为参数获取,如果服务器发现从此请求收到的用户ID并且 $ _ SESSION [“uid”] 匹配,则返回内容。

当我使用postman测试这两个代码时,GET请求会返回所需的响应,但是,当我在浏览器上测试相同时(从POST请求登录时从站点界面手动登录)然后请求来自地址栏的GET服务,它返回没有任何用户ID设置的错误消息(我把错误消息放在返回的json中检查是否(isset($ _ SESSION [“uid”]))为真,否则返回错误信息) 。 以下是代码:

[登录-POST]

<?php
    session_start();
    include_once $_SERVER['DOCUMENT_ROOT'].'/settings/ReadIni.php';
    include_once $_SERVER['DOCUMENT_ROOT'].getinivalue('Paths', 'database_connect_location');

    if( $_SERVER['REQUEST_METHOD'] == "POST" ) {
        if( $dberror == "" ) {
            if(isset($_SESSION["uid"])) {
                $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".getinivalue('ReturnValues', 'session_already_running'));
            }
            else
            {
                $indata = file_get_contents('php://input');
                $indata = json_decode($indata);

                $password = $indata->pass;
                $loginid = mysqli_real_escape_string($conn, $indata->loginid);
                $pass = mysqli_real_escape_string($conn, $password);

                if(($loginid != "") && ($pass != "")) {
                    $qrymailchk = "SELECT * from user_master where user_mail='$loginid'";
                    $qryphonechk = "SELECT * from user_master where user_phone='$loginid'";

                    $resmailchk = mysqli_query($conn, $qrymailchk);
                    $resphonechk = mysqli_query($conn, $qryphonechk);

                    $row1 = mysqli_fetch_array($resmailchk, MYSQLI_BOTH);
                    $row2 = mysqli_fetch_array($resphonechk, MYSQLI_BOTH);

                    if($row1 || $row2) {
                        $dbpass = ($row1) ? $row1['user_pass'] : $row2['user_pass'];
                        if ($pass == $dbpass) {
                            /*$passchk = password_verify($pass, $dbpass);*/

                            $_SESSION["uid"] = ($row1) ? $row1['user_code'] : $row2['user_code'];

                            $_SESSION["un"] = ($row1) ? $row1['user_name'] : $row2['user_name'];
                            $_SESSION["em"] = ($row1) ? $row1['user_mail'] : $row2['user_mail'];
                            $_SESSION["ph"] = ($row1) ? $row1['user_phone'] : $row2['user_phone'];

                            $words = explode(" ",$_SESSION["un"]);
                            $_SESSION["fn"] = $words[0];

                            $json = array("status" => getinivalue('ReturnValues', 'request_success'), "UserName" => $_SESSION["un"], "UID" => $_SESSION["uid"]);

        //                    $URL = "/services.php";
        //                    echo '<META HTTP-EQUIV="refresh" content="0;URL=' . $URL . '">';
        //                    echo "<script type='text/javascript'>document.location.href='{$URL}';</script>";
        //    
        //                    exit();
                        }
                        else {
                            $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".getinivalue('ReturnValues', 'invalid_credentials'));
                            mysqli_close($conn);
                        }                   
                    }
                    else{
                        $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".getinivalue('ReturnValues', 'invalid_credentials'));
                        mysqli_close($conn);
                    }
                }
            }
        }
        else {
            $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".$dberror);
        }
    }
    else {
        $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".getinivalue('ReturnValues', 'invalid_request_type'), "Required" => getinivalue('ReturnValues', 'request_type_post'));
    }

    header('Content-type: application/json');
    echo json_encode($json);        
?>

[目录-GET]

<?php
    session_start();
    include_once $_SERVER['DOCUMENT_ROOT'].'/settings/ReadIni.php';
    include_once $_SERVER['DOCUMENT_ROOT'].getinivalue('Paths', 'database_connect_location');

    if( $_SERVER['REQUEST_METHOD'] == "GET" ) {
        if( $dberror == "" ) {
            if(isset($_GET['uid'])) {
                $uid = $_GET['uid'];
                if(isset($_SESSION["uid"])) {
                    if($_SESSION["uid"] == $_GET['uid']) {
                        $qry1 = "SELECT device_code from user_device where user_code='".$uid."' and device_active='1'";
                        $res1 = mysqli_query($conn, $qry1);

                        $json = array("status" => getinivalue('ReturnValues', 'request_success'), "list_of_devices" => NULL);

                        if(mysqli_num_rows($res1)) {
                            $device_list = array();

                            while ($devices = mysqli_fetch_array($res1, MYSQLI_BOTH)) {
                                $qry2 = "SELECT device_name from device_master where device_code='".$devices[0]."'";
                                $res2 = mysqli_query($conn, $qry2);

                                $row = mysqli_fetch_array($res2, MYSQLI_BOTH);

                                $device_detail = array("device_code" => $devices[0], "device_name" => $row['device_name']);
                                array_push($device_list, $device_detail);
                            }

                            $json["list_of_devices"] = $device_list;    
                        }
                    }
                    else {
                        $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => getinivalue('ReturnValues', 'invalid_userid'));
                    }
                }
                else {
                    $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => getinivalue('ReturnValues', 'no_session'));
                }
            }
            else {
                $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => getinivalue('ReturnValues', 'input_not_set'));
            }    
        }
        else {
            $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".$dberror);
        }
    }
    else {
        $json = array("status" => getinivalue('ReturnValues', 'request_failure'), "message" => "Error: ".getinivalue('ReturnValues', 'invalid_request_type'), "Required" => getinivalue('ReturnValues', 'request_type_get'));
    }   

    header('Content-type: application/json');
    echo json_encode($json);
?>

请说明代码有什么问题,或者如果使用$ _SESSION变量有任何问题。

提前致谢。

1 个答案:

答案 0 :(得分:-1)

API并不意味着使用会话。 Session仅适用于浏览器。 您可以使用基于令牌的通信来维护用户信息。 在登录时,创建一个令牌,将其发送给客户端,客户端应该在每个请求中将令牌附加到api,以便服务器可以识别用户/对象/你想要的任何内容。

现在问题是有人可以修改令牌。使用jwt令牌可以避免这种情况。请参阅https://jwt.io/

JWT可用于创建由服务器签名的令牌,以便您可以确保第三方不会修改令牌。