troubleshooting Question

How to use session variables in php?

Avatar of Soumen Roy
Soumen RoyFlag for India asked on
RESTJSONPHP
22 Comments2 Solutions1173 ViewsLast Modified:
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.
ASKER CERTIFIED SOLUTION
Join our community to see this answer!
Unlock 2 Answers and 22 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 22 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros