如何在codeigniter中为rest调用生成令牌?

时间:2019-05-12 11:31:26

标签: rest codeigniter

我必须在codeigniter项目中调用rest api函数。数据是使用Postman从api调用返回的。在邮递员中,我首先生成一个令牌,然后将生成的令牌放入其余调用中。我必须在codeigniter中执行相同的过程。首先,我必须生成令牌并在第二次api调用中传递该令牌,以获得所需的结果。

我的控制器代码:

public function getToken()
{
        $url='http://localhost:8080/myapplication/rest/api/validate-request';
        $key=$this->get_data($url);
}
public function get_data($url)
{

    //create a new cURL resource
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");   
    //curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
    curl_setopt($ch, CURLOPT_USERPWD, R_U_NAME.':'.R_U_PWD);
    $result = curl_exec($ch);
    $result = json_decode($result);
    //var_dump($result);
    //close cURL resource
    curl_close($ch);


}

此处var_dump($ result)返回空值。

1 个答案:

答案 0 :(得分:1)

我不必通过用户名和密码进行身份验证。相反,我必须在函数中发布邮递员的用户名和密码。现在,我从邮递员那里拿回了令牌。

private function get_data($url)
    {   
        $member_data = array(
            'username' => R_U_NAME,
            'password' => R_U_PWD
        );
        //create a new cURL resource
        $ch = curl_init($url);

        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $member_data);

        $result = curl_exec($ch);

        curl_close($ch);

        return $result;
    }