Search code examples
phpphp-curl

Don't write to COOKIEFILE at a certain moment


How can I make it so that if the qwe value is found in cookies, then do not open the curl_setopt($ch, CURLOPT_COOKIEJAR, 'entry/cookies/test.txt');. I haven't figured out how to do it yet...

<?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]);
?>

Solution

  • You can't easily prevent PHP's cURL function from writing to the cookie file if you've already configured it to write to a cookie file.

    I suggest you first save the cookie file, fetch the URL, parse the headers to look for the string "qwe", and if not found, then restore the previous cookie file:

    $found_qwe = FALSE; // assume
    
    $cache_file = '/cookies/cache.txt';
    $cookie_file = '/cookies/test.txt';
    
    // Save cookies to cache:
    copy( $cookie_file, $cache_file );
    
    // https://stackoverflow.com/a/25118032/378779
    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