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

Unfortunately, I don't think you can use 'php://memory' as the input and output stream. The workaround is to parse the headers yourself. This can be done pretty easily. Here is an example of a page making two requests and passing the cookies yourself.

curl.php:

<?php

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localhost/test.php?message=Hello!');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_HEADER, true);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 

$data = curl_exec($curl);
curl_close($curl);

preg_match_all('|Set-Cookie: (.*);|U', $data, $matches);   
$cookies = implode('; ', $matches[1]);

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://localhost/test.php');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($curl, CURLOPT_HEADER, true);  
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($curl, CURLOPT_COOKIE, $cookies);

$data = curl_exec($curl);
echo $data;

?>

test.php:

<?php
session_start();
if(isset($_SESSION['message'])) {
    echo $_SESSION['message'];
} else {
    echo 'No message in session';
}

if(isset($_GET['message'])) {
    $_SESSION['message'] = $_GET['message'];
}
?>

This will output 'Hello!' on the second request.


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().


Just set CURLOPT_COOKIEFILE to a file that doesn't exist, usually an empty string is the best option. Then DON'T set CURLOPT_COOKIEJAR, this is the trick. This will prevent a file from being written but the cookies will stay in memory. I just tested this and it works (my test: send http auth data to a URL that redirects you to a login URL that authenticates the request, then redirects you back to the original URL with a cookie).


There is but it's completely unintuitive.

curl_setopt($curl, CURLOPT_COOKIEFILE, "");

For more details please see my answer in the comments


If using Linux, you could set these to point somewhere within /dev/shm .. this will keep them in memory and you can be assured that they won't persist across re-boots.

I somehow thought that Curl's cleanup handled the unlinking of cookies, but I could be mistaken.