Any Way to Keep Curl's Cookies in Memory and Not on Disk

Any way to keep curl's cookies in memory and not on disk

You can use the CURLOPT_COOKIEJAR option, and set the file to "/dev/null" for Linux / MacOS X or "NULL" for Windows. This will prevent the cookies from being written to disk, but it will keep them around in memory as long as you reuse the handle and don't call curl_easy_cleanup().

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

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!

Save cookies between two curl requests

Use the --cookie-jar or --dump-header parameter to save received cookies to a file. The --cookie parameter can read back the cookies from that file later.

-b, --cookie <name=data>

(HTTP) Pass the data to the HTTP server as a cookie. It is supposedly the data previously received from the server in a "Set-Cookie:" line. The data should be in the format "NAME1=VALUE1; NAME2=VALUE2".

If no '=' symbol is used in the line, it is treated as a filename to use to read previously stored cookie lines from, which should be used in this session if they match. Using this method also activates the cookie engine which will make curl record incoming cookies too, which may be handy if you're using this in combination with the -L, --location option. The file format of the file to read cookies from should be plain HTTP headers (Set-Cookie style) or the Netscape/Mozilla cookie file format.

The file specified with -b, --cookie is only used as input. No cookies will be written to the file. To store cookies, use the -c, --cookie-jar option.

Exercise caution if you are using this option and multiple transfers may occur. If you use the NAME1=VALUE1; format, or in a file use the Set-Cookie format and don't specify a domain, then the cookie is sent for any domain (even after redirects are followed) and cannot be modified by a server-set cookie. If the cookie engine is enabled and a server sets a cookie of the same name then both will be sent on a future transfer to that server, likely not what you intended. To address these issues set a domain in Set-Cookie (doing that will include sub-domains) or use the Netscape format.

If this option is used several times, the last one will be used.

-c, --cookie-jar <file name>

(HTTP) Specify to which file you want curl to write all cookies after a completed operation. Curl writes all cookies previously read from a specified file as well as all cookies received from remote server(s). If no cookies are known, no data will be written. The file will be written using the Netscape cookie file format. If you set the file name to a single dash, "-", the cookies will be written to stdout.

This command line option will activate the cookie engine that makes curl record and use cookies. Another way to activate it is to use the -b, --cookie option.

If the cookie jar can't be created or written to, the whole curl operation won't fail or even report an error clearly. Using -v will get a warning displayed, but that is the only visible feedback you get about this possibly lethal situation.

Since 7.43.0 cookies that were imported in the Set-Cookie format without a domain name are not exported by this option.

If this option is used several times, the last specified file name will be used.

-D, --dump-header <file>

Write the protocol headers to the specified file.

This option is handy to use when you want to store the headers that an HTTP site sends to you. Cookies from the headers could then be read in a second curl invocation by using the -b, --cookie option! The -c, --cookie-jar option is a better way to store cookies.

When used in FTP, the FTP server response lines are considered being "headers" and thus are saved there.

If this option is used several times, the last one will be used

Alternatively, instead of using the command-line cURL app, write some code that uses the libCurl library. That will give you more direct control over cookie handling. libCurl has several features related to HTTP cookies:

Options for curl_easy_getinfo():

  • CURLINFO_COOKIELIST - get all known cookies

Options for curl_easy_setopt():

  • CURLOPT_COOKIE - set contents of HTTP Cookie header

  • CURLOPT_COOKIEFILE - file name to read cookies from

  • CURLOPT_COOKIEJAR - file name to store cookies to

  • CURLOPT_COOKIESESSION - start a new cookie session

  • CURLOPT_COOKIELIST - add to or manipulate cookies held in memory

Then you can store the cookies however you want, and assign them as needed to later HTTP sessions.

how to handle curl session and cookies in php

You can modify

dirname(__FILE__) . "/cookies.txt"

Into something like

dirname(__FILE__) . '/user_cookies/' . $username . '.txt'

You will need to sanitize username for that line so that it will not contain any invalid characters.

Also, set /user_cookies/ permissions to something like 777.

This way you won't need to check if user has cookies or not. If not, the file will be created. If user has them, existing file content will be used.

You could also store cookies in database, but that's way more complicated.

Is there a way to keep a php object in memory to avoid disk reads and wirtes?

If it's a small object that doesn't take up much memory and is serializable you could just store it in the session:

function    getSessionObject($objectName, $params){

$sessionObjectSerialized = getSessionVariable($objectName, FALSE);

if($sessionObjectSerialized == FALSE){
$sessionObjectSerialized = constructSessionObject($objectName, $params);
setSessionVariable($objectName, $sessionObjectSerialized);
}

$sessionObject = unserialize($sessionObjectSerialized);

return $sessionObject;
}

function constructSessionObject($objectName, $params = array()){

switch($objectName){

case('gnugpg_key_ring'):{
$gnugpgKeyRing = getGNUPGKeyRing(); //do whatever you need to do to make the keyring.
return serialize($countryScheme);
}

default:{
throw new UnsupportedOperationException("Unknown object name objectName, cannot retrieve from session.");
break;
}
}
}

//Call this before anything else
function initSession(){
session_name('projectName');
session_start();
}

function setSessionVariable($name, $value){
$_SESSION['projectName'][$name] = $value;
}

function getSessionVariable($name, $default = FALSE){

if(isset($_SESSION['projectName'])){
if(isset($_SESSION['projectName'][$name])){
$value = $_SESSION['projectName'][$name];
}
}
return $default;
}

and then retrieve that object by calling

getSessionObject('gnugpg_key_ring');

However not all objects are always serializable e.g. if the object holds a file handle to an open file, that would need to have some extra code to close the file when the object is serialized and then re-open the file when the object was unserialized.

If the object is large, then you would be better off using a proper caching tool like memcached to store the serialized object, rather than the session.



Related Topics



Leave a reply



Submit