【问题标题】:How to use session variables in php?如何在php中使用会话变量?
【发布时间】:2017-08-29 12:56:06
【问题描述】:

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

如果登录成功,则设置一个 $_SESSION["uid"] 变量来检查 GET 响应是否来自同一用户。基本上,登录 api 从存储在 $_SESSION["uid"] 变量中的用户数据库中返回一个用户 ID。 GET请求读取内容,获取这个userid作为参数,如果服务器发现这个请求收到的userid和$_SESSION["uid"]匹配则返回内容。 p>

当我使用邮递员测试这两个代码时,GET 请求会返回所需的响应,但是,当我在浏览器上测试相同的响应时(从站点界面手动登录,因为从 POST 请求发生登录)然后请求从地址栏中获取 GET 服务,它返回没有设置任何用户 ID 的错误消息(我将错误消息放在返回 json 中以检查 if(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 变量的使用方式是否有任何问题。

提前致谢。

【问题讨论】:

  • 您是否在第二个请求中发送 PHPSESSID cookie?它的值是否与您从 POST 收到时的值相同?
  • 不,请告诉我更多关于 PHPSESSID cookie 的信息。该脚本实际上适用于站点的后端。我最近需要将它重写为 API,因为我的前辈要求我这样做,以便他可以使用该站点制作应用程序。我对 SESSIONS 和 COOKIES 知之甚少。
  • 我认为这些 URL 是从某种 JavaScript 调用的?你能在浏览器中查看对 /login 的 POST 调用的响应吗,在那里你应该看到服务器返回的所有 cookie,一个应该是 PHPSESSID 和一些散列字符串,然后比较你在 /contents GET 上发送的那个称呼。如果您还可以粘贴调用这些 URL 的 JavaScript 代码,那就太好了。
  • 不,当我调用上传到云端的脚本时,PHPSESSID cookie 不一样。但是当我从本地主机调用它们时,cookie 是相同的。

标签: php json session post get


【解决方案1】:

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

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

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

【讨论】:

  • 有人能告诉我这方面出了什么问题吗?有人投了反对票,我想知道错误的部分。
猜你喜欢
  • 2016-02-29
  • 1970-01-01
  • 2011-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-15
  • 1970-01-01
相关资源
最近更新 更多