【问题标题】:how to retain session when sending second request in curl php?在 curl php 中发送第二个请求时如何保留会话?
【发布时间】:2019-01-14 14:49:11
【问题描述】:

我的问题是,当我第一次将数据从 PHP 同步到 node js 时,我登录到 node.js 应用程序。但是当我在第二个请求上发送数据时登录后,会话没有发送 curl 请求,因此它显示“未登录”。

这是我的登录卷曲代码:

$data_string = json_encode(['userid' => $user_name, 'password' => $password]);
$URL = $url;     

$ch = curl_init('http://192.168.1.16:8000/auth/login');                                                                      
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data_string))                                                                 
);

$result = curl_exec($ch);

它正在发送数据卷曲代码:

$data_string = json_encode(['import_export' =>$json]);                                                                                   

https://stackoverflow.com/users
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => 'http://192.168.1.16:8000/api/all',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $data_string,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTPHEADER => array(                                                                          
            'Content-Type: application/json',                                                                                
            'Content-Length: ' . strlen($data_string)
        )
    ));

    $result = curl_exec($ch);

【问题讨论】:

  • 这是基于 cookie 的登录吗?然后继续阅读如何让 cURL 正确处理这些问题。
  • 我使用node session在nodejs API中存储登录信息。
  • Nodejs 不处理会话 cookie,Express 可以。
  • 是的,我使用 express 来创建服务器。

标签: php node.js session curl session-cookies


【解决方案1】:

告诉 cURL 使用 cookie:

curl_setopt(CURLOPT_COOKIEJAR, '/tmp/cookies.txt');
curl_setopt(CURLOPT_COOKIEFILE, '/tmp/cookies.txt');

这样,默认的基于 Node/Express 会话 cookie 的身份验证应该可以工作,因为会话 cookie 将在登录时保存并与后续请求一起发送。

http://php.net/manual/en/function.curl-setopt.php

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-06
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多