0

I am creating a login page in codeigniter where a user will give userid and password through an api(REST). When I run this page I get this error "Undefined index: userId". That means session data not found. I've read some older post about this topic but can't find any perfect solution. So I post here. Here is my controller page:

defined('BASEPATH') OR exit('No direct script access allowed');



class Login extends CI_Controller {

    public function index()
    {
        $this->load->helper('url');
        $this->load->library('session');

        $userId = $_SESSION["userId"];
        $token = $_SESSION["token"];

        $this->load->view('loginPage');
    }


    public function loginFromPanel()    
    {

        $this->load->library('session');
        $this->load->helper('url');
        session_start();
        $params   = $_SERVER['QUERY_STRING'];

        if(isset($params) && !empty($params)){
            $userInfo = explode('&', $params);
            $token = explode('=', $userInfo[0]);
            $token = $token[1];


            $userId = explode('=', $userInfo[1]);
            $userId = $userId[1];

            $_SESSION['token'] = $token;
            $_SESSION['userId'] = $userId;

        }


        if($_SESSION['userId'] == "")
        {
            redirect('login', 'refresh');
        }
        else
        {
            $_SESSION['userInfo'] = $userInfo;
            redirect('Instruction_page', 'refresh');
        }
    }

}

Here is the view page:


<html>
    <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Login</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Free HTML5 Website Template by freehtml5.co" />
    <meta name="keywords" content="free website templates, free html5, free template, free bootstrap, free website template, html5, css3, mobile first, responsive" />
    <meta name="author" content="freehtml5.co" />

    <!-- Facebook and Twitter integration -->
    <meta property="og:title" content=""/>
    <meta property="og:image" content=""/>
    <meta property="og:url" content=""/>
    <meta property="og:site_name" content=""/>
    <meta property="og:description" content=""/>
    <meta name="twitter:title" content="" />
    <meta name="twitter:image" content="" />
    <meta name="twitter:url" content="" />
    <meta name="twitter:card" content="" />

    <link href="https://fonts.googleapis.com/css?family=Space+Mono" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Kaushan+Script" rel="stylesheet">

    <!--Popup API-->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" crossorigin="anonymous">
  <!--Popup Api-->

    </head>
    <body>

    <div class="fh5co-loader"></div>

    <div id="page"> 
    <header id="fh5co-header" class="fh5co-cover js-fullheight" role="banner" data-stellar-background-ratio="0.5">

        <div class="container">
            <h2>Login</h2>
            <div class="row main">

                <div class="main-login main-center">
                    <form  class="form-horizontal" method="post" action="#">

                        <div class="form-group">
                            <label for="username" class="cols-sm-2 control-label">Username</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <input type="text" class="form-control" name="username" id="username"  placeholder="Username"/>
                                </div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="password" class="cols-sm-2 control-label">Password</label>
                            <div class="cols-sm-10">
                                <div class="input-group">
                                    <input type="password" class="form-control" name="password" id="password"  placeholder="Password"/>
                                </div>
                            </div>
                        </div>

                        <div class="form-group ">
                            <div type="submit" value="submit" class="btn btn-primary" id="loginForm">Submit</div>
                        </div>

                    </form>
                </div>
            </div>
        </div>

    </header>
</div>

    <div id="fh5co-footer">
        <div class="container">
            <div class="row">
                <div class="col-md-12">
                    <p>&copy; 2019 Total Gas</p>
                </div>
            </div>
        </div>
    </div>

    <div class="gototop js-top">
        <a href="#" class="js-gotop"><i class="icon-arrow-up22"></i></a>
    </div>

    <!--Popup API-->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.js"></script>
<script src="http://user.onukit.com/6v0/js/socket.io/node_modules/socket.io-client/dist/socket.io.js"></script>


<script>
    $('#loginForm').click(function(){
        var username = $('#username').val(); 
        var password = $('#password').val();
        console.log(username);
        console.log(password);

        $.ajax({
            type: "POST",
            url: "http://api.onuserver.com/6v1.1/login_api/loginApi",
            headers: {
                'Authorization': 'Basic ' + btoa(username+':'+password)
            },
            success: loginSuccess
        });
    });

    function loginSuccess(response) {
        response = JSON.parse(response);
        token = response.userToken.token;
        userId = response.userId;
        query_param = '?token='+token+'&userId='+userId;
  window.location.replace("http://demo.onuserver.com/CallLoyality/login/loginFromPanel/"+query_param);

    }

</script>

    </body>
</html>

and here is the api:


/**
 * Example
 *
 * This is an example of a few basic user interaction methods you could use
 * all done with a hardcoded array.
 *
 * @package     CodeIgniter
 * @subpackage  Rest Server
 * @category    Controller
 * @author      Phil Sturgeon
 * @link        http://philsturgeon.co.uk/code/
*/

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH.'/libraries/REST_Controller.php';

class loginApi extends REST_Controller
{

    function __construct() 
    {

        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if($method == "OPTIONS") {
            die();
        }
        parent::__construct();              
        $this->isSuccessfulLogin = false;       
        $this->load->model('login_model');
        $this->load->library('encrypt');
    }

    protected $rest_format   = 'application/json'; 

    function _perform_library_auth($username = '', $password = NULL)
    {

        $this->username = $username;
        $this->password = $password;

        $this->load->model('login_model');

        $isSuccessfulLoginArray= $this->login_model->getUserInfo($username, md5($password));

        $this->userData = $isSuccessfulLoginArray;


        if(empty($isSuccessfulLoginArray))
        {
            $responseData = array(
                    'status'    =>4200,
                    'success'   =>false,
                    'isActive'  =>false,
                    'reason'    =>'Username or password !'
            );

            $json_data = json_encode($responseData);

            $this->response($json_data ,200); 
        }else{
            return $this->userData = $isSuccessfulLoginArray;
        }
    }


    public function index_post()
    {

        $requestUserDetails = $this->userData;
        $userId = $requestUserDetails['id'];
        $parentId = $requestUserDetails['parent_user'];

        $token = $this->login_model->userToken($userId);


        $responseData['userId'] = $userId;
        $responseData['hashUserId'] = $this->encrypt->encode($userId);
        $responseData['parentId'] = $parentId;
        $responseData['userToken'] = $token;

        $json_data = json_encode($responseData);

        $this->response($json_data ,200);
    }   
}```

I'm using codeigniter 3. Please someone help me to find what's wrong in my code.
3
  • 1
    Possible duplicate of How to check if an array element exists? Commented Jul 28, 2019 at 7:24
  • no it doesn't solve my problem Commented Jul 28, 2019 at 8:07
  • Is the problem that the session value should be set but can't be found? Or that the session is not set and you're getting an "undefined index" error? Commented Jul 28, 2019 at 8:13

0

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.