如何在单个页面的PHP中保存会话Angular 2的应用程序

时间:2017-05-06 08:18:54

标签: php angular session post

在Angular2 App中,当我从LoginComponent登录时,会在PHP服务器中成功创建Session变量。

但是当我的应用程序更改其路径到其他组件(例如:Eg:SchoolsListComponent)然后它从PHP服务器请求某些内容时,我注意到会话变量根本不存在。

当我从我的SchoolListComponent

调用get_schools_list.php时发生以下错误
  

未定义索引:id in    C:\ xampp \ htdocs \ myapp \ admin \ session_secure.php 在线    3

在PHP Server中我有以下文件

  1. 的login.php。
  2. session_secure.php。
  3. get_schools_list.php。
  4. angular_cors_fix.php。
  5. db_connect.php。
  6. 在Angular2中,我有以下组件

    1. LoginComponent。
    2. SchoolsListComponent。
    3. 以下是每个文件的代码

      1. LoginComponent类:

        phpUrl = "http://192.168.43.162/myapp/admin/";
        login(username:string, password:string){
           let postdata = {
             username : username,
             password : password
           }
           let headers = new Headers();
           headers.append('Content-Type','application/x-www-form-urlencoded');
           return this.http.post(`${this.phpUrl}loginAdmin.php`,postdata,{
             headers : headers
           }).subscribe(
               (response : Response)=>{
                  let data = response.json();
                  if(data.success == 1){
                     this.router.navigate(["/schools_list"]); //Routing to My Main Component
                  }
               }
           );
        }
        
      2. SchoolListComponent Class:

        phpUrl = "http://192.168.43.162/myapp/admin/";
        constructor(){ this.getSchools(); }
        getSchools(){
           let post_data = {
               some_post_data : "data"
           }
           let headers = new Headers();
           headers.append('Content-Type','application/x-www-form-urlencoded');
           let myObserver = this.http.post(`${this.phpUrl}get_schools_list.php`,post_data,{
             headers : headers
           });
        
           myObserver.subscribe(
             (data : Response)=>{
               let session = data.json();
               if(session.loggedIn == false){
                 this.router.navigate(["/login"]);
               }
             }
           );
           return myObserver;
        }
        
      3. login.php

        <?php
        require "angularfix.php";
        require "db_connect.php";
        $response = array();
        $data = json_decode(file_get_contents("php://input"));
        $username = $data->username;
        $password = $data->password;
        if (!preg_match('/[\'^£$%&*()}{#~?><>,|=+¬-]/', $username)){    
           $query ="SELECT * FROM `admin` WHERE `username` = '$username' AND `password` = '$password'";
           if($result = mysqli_query($database,$query)){
               if($row = mysqli_fetch_array($result)){
                   $response['success'] = 1;
                   $response['message'] = "Successfully logged in !!";
                   $response['admin_id'] = $row['admin_id'];
                   session_start();
                   $_SESSION['id']=session_id();//Here i initialized session id
                   $response['id'] = $_SESSION['id'];
                   $response['savepath'] = session_save_path();
                   storeIntoSessionAdminId($response['admin_id']);
        
               }else{
                   $response['success'] = 0;
                   $response['message'] = "Username or Password Invalid";
                   $response['error'] = "Username or Password Invalid";
               }
           }else{
               $response['success'] = 0;
               $response['message'] = "Error in Server";
               $response['error'] = "".mysqli_error($database)."";
           }
        }else{
           $response['error'] = "Special characters not allowed";
           $response['success'] = 0;
        }
        // echoing JSON response
        echo json_encode($response);
        function storeIntoSessionAdminId($id){
            $_SESSION['admin_id']=$id;
        }
        ?>
        
      4. session_secure.php

        <?php
        session_start();
        $response = array();
        if($_SESSION['id'] == session_id()){
            $response['admin_id'] = $_SESSION['admin_id'];
            $response["loggedIn"] = true;
            $response['message'] = "user has session !!!";
            $response['success'] = 1;
        }
        else{
            $response["loggedIn"] = false;
            $response['message'] = "user dont have any session !!!";
            $response['success'] = 0;
            echo json_encode($response);
            exit();
        }
        ?>
        
      5. get_schools_list.php

        <?php
        require "angular_cors_fix.php";
        require "session_secure.php";
        require "db_connect.php";   
        $response["schools"] = array();
        $query = "SELECT * FROM school";
        if($result = mysqli_query($database,$query)){
            if(mysqli_num_rows($result)){
                while ($row = mysqli_fetch_array($result)) {
                    $temp                   = array();
                    $temp["school_id"]      = $row["school_id"];
                    $temp["school_name"]    = $row["school_name"];
                    $temp["data_phase"]     = $row["data_phase"];
                    $temp["school_address"] = $row["school_address"];
                    $temp["city"]           = $row["city"];
                    $temp["pincode"]        = $row["pincode"];
                    $temp["total_students"] = $row["total_students"];
                    $temp["head_name"]      = $row["head_name"];
                    array_push($response["schools"],$temp);
                }
                $response['success'] = 1;
                $response['message'] = "Data Available";
            }else{
                $response['success'] = 0;
                $response['message'] = "Data Not Available";
            }
        }
        $response["success"] = 1;
        $response["message"] = "Data Available";
        echo json_encode($response);
        ?>
        
      6. angular_cors_fix.php:

        <?php
           header("Content-Type: application/json; charset=UTF-8");
           header('Access-Control-Allow-Origin: *');
           header('Access-Control-Allow-Methods: GET, POST');
        ?>
        
      7. db_connect.php:

        <?php
          date_default_timezone_set('Asia/Kolkata');
          $database = mysqli_connect('localhost', 'root', '', 'myapp')
             or die(mysqli_error($database));   
        ?>
        
      8. 我的应用程序流程如下

        1. LoginComponent:

          • 登录请求服务器“Login.php”创建会话。

          • 成功登录时重定向到SchoolListComponent。

        2. SchoolListComponent:

          • 请求学校JSON服务器,并检查会话

          • 如果会话不存在,则重定向到LoginComponent。

          • 如果会话存在,则在模板中显示学校列表。

        3. 我已粘贴所有文件,因为我认为问题可能是由于多种原因造成的:

          1. CORS问题。
          2. 单页申请。
          3. 接头
          4. PHP Sessions。
          5. Angular2 / PHP本身。
          6. 请指导我如何解决这个问题的会议谢谢..

0 个答案:

没有答案