繁体   English   中英

在codeigniter php中与cURL保持会话

[英]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以便在下次执行时生成并使用新的sid

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM