Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
477 views
in Technique[技术] by (71.8m points)

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

I'm doing some cURL work in php 5.3.0.

I'm wondering if there is any way to tell the curl handle/object to keep the cookies in memory (assuming I'm reusing the same handle for multiple requests), or to somehow return them and let me pass them back when making a new handle.

Theres this long accepted method for getting them in/out of the request:

curl_setopt($ch, CURLOPT_COOKIEJAR, $filename); 
curl_setopt($ch, CURLOPT_COOKIEFILE, $filename);

But I'm hitting some scenarios where I need to be running multiple copies of a script out of the same directory, and they step on each others cookie files. Yes, I know I could use tempnam() and make sure each run has its own cookie file, but that leads me to my 2nd issue.

There is also the issue of having these cookie files on the disk at all. Disk I/O is slow and a bottle neck I'm sure. I dont want to have to deal with cleaning up the cookie file when the script is finished (if it even exits in a way that lets me clean it up).

Any ideas? Or is this just the way things are?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...