不要在某个时刻写入 COOKIEFILE

Don't write to COOKIEFILE at a certain moment

如果在 cookie 中找到 qwe 值,我怎样才能不打开 curl_setopt($ch, CURLOPT_COOKIEJAR, 'entry/cookies/test.txt');。我还没想好怎么办...

<?php
$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://site.ru');
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_COOKIEFILE, '/cookies/test.txt');
curl_setopt($ch, CURLOPT_COOKIEJAR, '/cookies/test.txt');

$response = curl_exec($ch);

curl_close($ch);

preg_match_all('|Set-Cookie: (.*);|U', $headers, $parse_cookies);

if(isset($parse_cookies[1]) && !$parse_cookies[1]) {
 preg_match_all('|Set-Cookie: (.*?)|U', $headers, $parse_cookies);
}

$cookies = implode(';', $parse_cookies[1]);
?>

如果您已经将 PHP 的 cURL 函数配置为写入 cookie 文件,则无法轻易阻止其写入 cookie 文件。

我建议你先保存cookie文件,取URL,解析headers寻找字符串“qwe”,如果没有找到,再恢复之前的cookie文件:

$found_qwe = FALSE; // assume

$cache_file = '/cookies/cache.txt';
$cookie_file = '/cookies/test.txt';

// Save cookies to cache:
copy( $cookie_file, $cache_file );

// 
function myFilter( $ch, $header_line ) {
    global $found_qwe;

    // Examine this line from the header:
    if ( preg_match( '/Set-Cookie: qwe/i', $header_line ) ) {
        $found_qwe = TRUE;
    }

    return strlen( $header_line );
}

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'http://site.ru');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'myFilter');

$response = curl_exec($ch);

// If we found "qwe", restore the old cookie file:
if ( $found_qwe ) {
    // Restore cookies:
    copy( $cache_file, $cookie_file );
}

unlink( $cache_file ); // optional