【问题标题】:session id extraction from a curl response从 curl 响应中提取会话 ID
【发布时间】:2014-11-13 05:42:57
【问题描述】:

我得到如下格式的 curl 响应。

HTTP/1.1 200 OK Date: Thu, 13 Nov 2014 05:34:03 GMT Server: Apache/2.4.9 (Ubuntu) Set-Cookie: sid=o58lq30rgnqsep720kbje8cap5; path=/ Cache-Control: no-cache Allow: POST Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8 {"Response":{"reasonCode":"0","reasonText":"The consumer was successfully logged in with a session cookie","reasonImageURL":"","satn":"213456","rrn":"1415856843"}}

我想获取会话 ID 来存储它。我尝试了一些链接来解决它,但没有任何效果。请帮忙!!

【问题讨论】:

    标签: php session curl


    【解决方案1】:

    这应该会有所帮助

    preg_match('/SID=(\w+)/', $response['body'], $matches);
    $sid = $matches[1]; //sid
    

    【讨论】:

    • 这行不通。首先,它与 OP 的字符串不匹配,因为您没有使用 i 标志。其次,您必须使用 \w+ 而不是 .+ 否则它会在sid= 部分之后捕获所有内容(直到新行)。
    • 嗨,Himal,这是正确的。我添加了 \w+ 而不是 .+ 并且它起作用了。谢谢
    【解决方案2】:

    要正确解决此问题,您应该正确解析 HTTP 响应...

    $response = "";
    list($headers, $body) = explode("\r\n\r\n", $response, 2);
    $raw_headers = explode("\r\n", $headers);
    array_shift($raw_headers); // exclude first row 'HTTP/1.1 200 OK'
    $headers = array();
    foreach($raw_headers as $header) {
      list($key, $value) = explode(": ", $header, 2);
      $headers[strtoupper($key)] = $value;
    }
    $cookie = $headers['SET-COOKIE'];
    preg_match('/sid=([a-f\d])/i', $cookie, $matches);
    if ($matches) {
      $session_id = $matches[1];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-04
      • 2021-07-29
      • 2019-10-12
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多