如何将一个函数的计算值/最终值传递给Codeigniter应用程序控制器中的其他函数

eagi6jfj  于 2022-12-16  发布在  其他
关注(0)|答案(2)|浏览(83)

使用会话我们可以实现这一点,但需要在没有会话或Cookie的情况下实现这一点。

<?php
    class Employees extends CI_Controller
    {
    
      public function __construct()
      {
        parent::__construct();
      }
    
       public function auth() {
       
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
             $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
             //if user exist
             if ($query->num_rows() <= 0) {
                $response = array();
                 $jwtoken = "";
                 $this->session->set_flashdata("invalid", "Wrong email or password"); 
                 $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $jwtoken,
                );
                //used to send finalized values 
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
             } else {   
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                  if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $jwtoken
                    );
                 }
                 $abc = $jwtoken;
                 //used to send finalized values 
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
             } 
        }
     }
    
    
       public function addNew()
      {
         $response = array();
          
         $this->auth(); // this value is always null returned by auth() method
      }
    }
?>
368yc8dk

368yc8dk1#

这更多的是一个面向对象编程的基础问题。如果你想在同一个控制器对象的另一个函数中重用一个变量,你必须为Employees类全局设置变量,然后通过使用$this-〉yourVariableName在你的函数中设置/获取它的值。但是对象示例的设置值只能在那个示例中重用。这意味着在授权之后()函数,则随后应调用另一个函数来“访问”$this-〉yourVariableName。另一种方法是将$jwtoken作为参数传递给函数。
但是下面的代码回答了你的问题“如何将一个函数的计算值/最终值传递给Codeigniter应用程序控制器中的其他函数",如果没有,那么我猜你的问题应该得到纠正。

**编辑:**Ow ok,首先auth()函数被调用,然后你想把$jwtoken值传递给另一个函数,对吗?一旦函数执行完毕,如果没有传递给另一个函数,变量就会“消失”。如果你想在auth()函数中立即处理$jwtoken值,那么答案是从auth()函数中把$jwtoken值传递给另一个函数:

<?php
class Employees extends CI_Controller
{
    public function __construct() {
        parent::__construct();
    }

    public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                $this->session->set_flashdata("invalid", "Wrong email or password");
                $response = array(
                    'status' => 'invalid',
                    'message' => $_SESSION['invalid'],
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                
                // this is one way you can pass the value to another function, depending on what you want to do, you can also place a condition and continue only if the return value of the following function is respected:
                $this->addNew($jwtoken);
                // What is the addNew() supposed to do?

                $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => $_SESSION['login'],
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

    public function addNew($jwtoken = "default_value_if_not_set") {
        echo $jwtoken;
    }
}
vyu0f0g1

vyu0f0g12#

由于您正在创建一个API,我假设该API是一个REST API并且是无状态的,因此不存在会话和cookie的干扰。
我假设您的流程是这样的:

  • 用户从应用程序向API发出登录请求,当凭据检查有效时,api将返回一个令牌
  • 令牌存储在应用程序中(例如,本地数据库中)并用于其他请求

所以你需要做的唯一一件事就是(我假设你有一个addNew的路径):

public function addNew() {
    $token = $this->input->get('token');
    $loginData = $this->validateToken($token);
    //... add new process 
}

并且您需要从应用程序将令牌与请求一起传递给API。

如何验证令牌?

要获取您在令牌中设置的数据,必须对令牌进行解码:

/**
 * throws SignatureInvalidException
 */
function validateToken($token) 
{
   $jwt = new JWT();
   return $jwt->decode($token, jwtSecretKey, 'HS256');
}

代码改进

避免使用会话和Cookie

由于你的API是无状态的,你必须避免设置cookie或会话,所以在你的控制器中你可以删除flash数据助手:

public function auth() {
        $adminEmail = $this->input->post('adminEmail');
        $adminPassword =  $this->input->post('adminPassword');
        if ($adminEmail != "" && $adminPassword != "") {
            $query = $this->db->query("select * from admin_tbl where email= '$adminEmail' and password = '$adminPassword'");
            //if user exist
            if ($query->num_rows() <= 0) {
                $response = array();
                $jwtoken = "";
                
                # REMOVE THIS LINE 
                # $this->session->set_flashdata("invalid", "Wrong email or password");

                $response = array(
                    'status' => 'invalid',
                    'message' => "Wrong email or password", //CHANGE THIS LINE
                    'token' => $jwtoken,
                );
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken;  //return value
            } else {
                //  $this->session->set_userdata('adminEmail', $adminEmail);
                $response = array();
                $jwt = new JWT();
                $data = array(
                    'adminEmail' => $adminEmail,
                    'iat' => time()
                );
                $jwtoken = $jwt->encode($data, jwtSecretKey, 'HS256');
                // I want to pass $jwtoken's variable to all the functions in a controller
                # REMOVE THIS LINE
                # $this->session->set_flashdata("login", "Scucessfully login!");
                //  if (isset($_SESSION['adminEmail'])) {
                if ($jwtoken != "") {
                    $response = array(
                        'status' => 'valid',
                        'message' => "Scucessfully login!", //CHANGE THIS LINE 
                        'token' => $jwtoken
                    );
                }
                $abc = $jwtoken;
                //used to send finalized values
                $this->output
                    ->set_content_type('application/json')
                    ->set_output(json_encode($response));
                return $jwtoken; //return value
            }
        }
    }

返回输出响应而不是$jwtoken

在您的响应中,您已经设置了标记,因此您可以简单地返回响应:

return $this->output
    ->set_content_type('application/json')
    ->set_output(json_encode($response));

您的查询容易受到SQL注入的攻击

在变量周围使用转义方法或绑定参数:

$sql = "select * from admin_tbl where email=? and password = ?";
$query = $this->db->query($sql, array($adminEmail, $adminPassword));

相关问题