在 codeigniter 中使用 cURL 保持会话 php

Keep session with cURL in codeigniter php

我有一个外部 API,我想在其中获取一些数据,并且我想在所有请求中保留会话 ID,直到我注销。在 codeigniter 中使用 cURL lib 我有以下流程(myacc 和 mypass 只是占位符):

public function getCURL() {
   echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');
}

这将输出:

{"data":{"sid":"lH6WJCWMm5rkA14B0MPN570354"},"success":true}

在发出下一个请求时,我必须保留提供的 sid(会话 ID):

http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2&timestamp=1480512959&preview=true&_sid="lH6WJCWMm5rkA14B0MPN570354"

见文末sid="lH6WJCWMm5rkA14B0MPN570354".

然后注销并杀死那个 sid。

每次登录后,我都会得到一个新的 sid,我必须用它来获取图片(使用那个 URL),然后注销。

我认为在我的案例中不需要保存和使用文件中的 cookie,我认为是这样的:

public function getCURL() {
   echo $this->curl->simple_get('http://37.99.210.237:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');

   if ($this->form_validation->run()){
            $data= array(
                'sid'=> $this->input->post('sid'),
                'is_logged_in' => true
            );
$this->session->set_userdata($data);

if(false == $this->CI->session->userdata('is_logged_in')) {
       echo $this->curl->simple_get('http://37.99.110.537:6001/webapi/entry.cgi?api=SYNO.SurveillanceStation.Camera&method=GetSnapshot&version=1&cameraId=2&timestamp=1480512959&preview=true&_sid="sid"');

}

}
}

^^ 该语法一团糟,但我如何才能以正确的方式实现它,或者如何将会话 ID 保留在请求链上?

如果您想为长时间会话、多个请求等保留 sid,您可以将此 json 保存到某个 json 文件并在注销时清除文件内容。

将您的 $sid getter 包装到其他函数。

function getSid()
{
    //try to read from json
    if(is_file('path/to/sid.json'){
        $sid = json_decode(file_get_contents('path/to/sid.json', true));
        if(!isset($sid['logout'])){
            return $sid['data']['sid'];
        }
    }
    $sid = $this->curl->simple_get('http://37.99.110.537:6001/webapi/auth.cgi?api=SYNO.API.Auth&method=login&version=2&account=myacc&passwd=mypassD&format=sid&session=SurveillanceStation');

    //check and save `$sid`

    if(strlen($sid) > 20) {
        file_put_contents('path/to/sid.json', $sid);
        return json_decode($sid, true)['data']['sid'];
    }
    return false;
}

并在注销时更新 sid.json 的内容。

function logout()
{
    file_put_contents('path/to/file', json_encode(['logout' => 'true']));
}

并调用这些方法。

对于一次执行中的每个请求,它将使用相同的 sid,当您点击 'logout()' 时,它将销毁 sid,以便新生成并用于下次执行。