0

I have built a few crude rest apis that return json response. One api accepts POST request and is used to login a user, and another accepts GET request and reads contents for user from database.

If the login occurs successfully, a $_SESSION["uid"] variable is set for checking if the GET response occurs from the same user. Basically, the login api returns a userid from the users database that is stored in the $_SESSION["uid"] variable. The GET request to read contents, gets this userid as a parameter, and if the server finds that the userid received from this request and $_SESSION["uid"] match then the contents are returned.

When I test the two codes using postman, the GET request returns the desired response, however, when I test the same on the browser (logging in manually from the site interface as the login occurs from a POST request) and then request the GET service from the address bar, it returns error message of not having any userid set (I put the error message in the return json to check if(isset($_SESSION["uid"])) is true else return error message). Following are the codes:

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

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

Please suggest what is wrong with the codes or if there is being any problem with how $_SESSION variables are used.

Thanks in advance.

4
  • Are you sending the PHPSESSID cookie on the second request? Does it have the same value as when you received it from the POST? Commented Apr 4, 2017 at 11:03
  • No, please tell me more about the PHPSESSID cookie. The script acually worked for the backend of a site. I recently needed to rewrite it as an API as my senior asked me to do it so he could make an App with this site. I have very little knowledge about SESSIONS and COOKIES. Commented Apr 4, 2017 at 11:06
  • I presume those URLs are called from some sort of JavaScript? Can you check in the browser the response of the POST call to /login, there you should see all the cookies that the server returns, one should be PHPSESSID with some hashed string, then compare the one that you are sending on the /contents GET call. If you could also paste the JavaScript code that calls those URLs this would be nice as well. Commented Apr 4, 2017 at 11:11
  • No, the PHPSESSID cookies are not same when I call the scripts uploaded on cloud. But the cookies are same when I call them from my localhost. Commented Apr 4, 2017 at 11:24

1 Answer 1

1

APIs are not meant to use sessions. Session works with browsers only. You can use token based communications for maintaining user information. On login, create a token, send this to client, client should append the token in every request to the api, sothat the server can identify the user/object/whatever you want.

Now the issue is somebody can modify the token. THis can be avoided by using jwt tokens. Refer to https://jwt.io/

JWT can be used to create tokens that are signed by the server so that you can make sure the token is not modified by third party.

Sign up to request clarification or add additional context in comments.

1 Comment

Can somebody give me an idea of what went wrong on this. Some one voted down the answer, I would like to know the wrong part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.