PHP curl_close 后未保存 cURL cookie

PHP cURL cookie not saved after curl_close

我无法在 curl_close() 之后访问 cookie 文件,尽管它已成功创建(不是文件路径问题)。因此,我在 curl_close() 之后添加了 15 秒的睡眠,我注意到 cookie 文件仅在 15 秒后创建,即在整个 php 文件结束后创建。

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

根据 curl_close 的手动输入:

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

这个原因在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.

要释放 cookie 文件资源,您需要 unset curl 句柄:

unset($ch);