Sunday, September 4, 2022

[SOLVED] PHP cURL cookie not saved after curl_close

Issue

I couldn't access the cookie file after curl_close() although it's created successfully (not a file path issue). So, I added a 15 seconds of sleep after curl_close() and I noticed that the cookie file is created only after the 15 seconds, i.e. after the whole php file ends.

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
        $response = curl_exec($ch);
        curl_close($ch);

        //I can't find the cookie file here
    
        sleep(15);

Solution

According to the manual entry for curl_close:

This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.

This reason is explained in this article :

From PHP 8 and forward, curl_init function returns an instance of \CurlHandle class

Because the handlers are now objects, the resources will be destroyed during garbage collection, unless the handler is explicitly closed with an unset() call.

To release the cookie file resource you need to unset the curl handle :

unset($ch);


Answered By - user973254
Answer Checked By - Katrina (WPSolving Volunteer)