PHP - Using cURL to store cookie session into variable / memory

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

I'm trying to avoid cURL storing the cookie session into an actual file via "CURLOPT_COOKIEJAR". So I created a method to catch / parse the cookies into a local variable - which is then used via "CURLOPT_COOKIE" to restore the cookie session.

I cut out the cookies via

preg_match_all("/^Set-cookie: (.*?);/ism", $header, $cookies);

To use "CURLOPT_COOKIE" we take the key=value and separate them via "; ". However (As I'm aware), CURLOPT_COOKIE doesn't allow you throw in various flags I.e. expiration, secure flag, and so on.

Update 1/29/2014 6:45pm

So I think my issue actually occurs where CURLOPT_FOLLOWLOCATION occurs. I don't think it has to do with the flags. It doesn't seem like the manual cookie session I have is updating when following a new location (i.e. a site has 2-3 redirects to append various cookies / session). Which would actually make sense because utilizing CURLOPT_COOKIEJAR will directly grab / update cookies sent on header redirects. So, I tried creating a manual redirection path while grabbing / appending the latest cookie - however this method did not work for some plain reason.

Update 1/30/2014 4:22pm

Almost got this figured out. Will be updating with answer shortly. It turns out my method works perfectly fine, it's just a matter of jumping through the manual redirected pages correctly.

Update 1/30/2014 4:51pm Issue solved -- answered myself below.

回答1:

So it turns out I was actually doing this correctly and my assumptions were correct.

  1. To keep the cookie session in a variable (vs. CURLOPT_COOKIEJAR). *Make sure you have CURLOPT_HEADER and CURLINFO_HEADER_OUT enabled.*

  2. CURLOPT_FOLLOWLOCATION must be set to false. Otherwise your cookie won't send correctly (This is where CURLOPT_COOKIEJAR does best).

  3. Use preg_match_all to extract cookies. Then use strpos to find the first occurence of "=". Some sites use encoding and include "="'s which won't work with "explode".

    $data        = curl_exec($curl); $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $header      = substr($data, 0, $header_size);  preg_match_all("/^Set-cookie: (.*?);/ism", $header, $cookies); foreach( $cookies[1] as $cookie ){     $buffer_explode = strpos($cookie, "=");     $this->cookies[ substr($cookie,0,$buffer_explode) ] = substr($cookie,$buffer_explode+1); }
  4. When making your next curl call, re-call the cookie var/object into CURLOPT_COOKIE.

    if( count($this->cookies) > 0 ){     $cookieBuffer = array();     foreach(  $this->cookies as $k=>$c ) $cookieBuffer[] = "$k=$c";     curl_setopt($curl, CURLOPT_COOKIE, implode("; ",$cookieBuffer) ); }

This will allow you to keep the latest variable (i.e. changing sessions) intact.

Hope this helps anyone who bumps into this issue!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!