繁体   English   中英

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

[英]How to use session variables in php?

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

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

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

[登录后]

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

[Contents-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变量的使用方式是否有问题。

提前致谢。

API不能使用会话。 会话仅适用于浏览器。 您可以使用基于令牌的通信来维护用户信息。 登录时,创建令牌,并将其发送给客户端,客户端应将令牌添加到api的每个请求中,以便服务器可以识别用户/对象/所需对象。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM