php curl不会写cookie文件

I know there are loads of question like this, but could anyone help me narrow down what the issue is?

This is my code:

ini_set("display_errors", 1);
error_reporting(E_ALL);
$cookies = 'cookies.txt';
$postdatal = array(
    '__VIEWSTATE' => '', // need a __VIEWSTATE, even if it's empty
    'username' => 'username',
    'password' => 'password',
    'button1' => 'Sign+in', // need button1
    '__VIEWSTATEGENERATOR' => '' // same reason as __VIEWSTATE
);

$ch = curl_init();

curl_setopt_array( 
$ch, array(
    CURLOPT_URL => 'url',
    CURLOPT_RETURNTRANSFER => true, // return the results
    CURLOPT_POST => true, 
    CURLOPT_POSTFIELDS => $postdatal, // send the data
    CURLOPT_HEADER => true,
    CURLOPT_COOKIEJAR => $cookies, // set the cookies
    CURLOPT_COOKIEFILE => $cookies 
));

$output = curl_exec($ch);

echo $output;

The headers returned have three Set-Cookie headers. Is there any way I could debug this? I don't seem to get any errors, even if I choose an invalid file name (cookies.txt is a chmod 777 empty text file).

I solved my problem: I needed to add curl_close() in order for the cookie file to be saved.