unable to write to file with PHP cURL with curlopt_stderr and curlopt_file unable to write to file with PHP cURL with curlopt_stderr and curlopt_file curl curl

unable to write to file with PHP cURL with curlopt_stderr and curlopt_file


Note: If the URL you are trying to curl redirects to another URL, then writing output to a file WILL fail.

Please make sure you add the following line also-

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

Also as a side note, make sure you close the file with fclose() to make sure the file is complete.


If you've added fclose(), and made the various "little fixes" listed in the comments above, but it's still not working... then I suspect that you're seeing conflicting options:

  • CURLOPT_RETURNTRANSFER tells curl to return the response as the return value of the curl_exec() call.

  • CURLOPT_FILE and CURLOPT_STDERR tell curl to write the response (or error output) to a specified file handle.

Seems like these may be mutually exclusive. I would suggest that you use one or the other, but not both:

Either use CURLOPT_RETURNTRANSFER, like this:

$session = curl_init();$logfh = fopen("my_log.log", 'a+');if ($logfh !== false) {  print "Opened the log file without errors";}curl_setopt($session, CURLOPT_HEADER, false);curl_setopt($session, CURLOPT_RETURNTRANSFER, true);curl_setopt($session, CURLOPT_VERBOSE, true);$result = curl_exec($session);curl_close($session);fwrite($logfh, $result);fclose($logfh);

or use CURLOPT_FILE, like this:

$session = curl_init();$logfh = fopen("my_log.log", 'a+');if ($logfh !== false) {  print "Opened the log file without errors";}curl_setopt($session, CURLOPT_HEADER, false);curl_setopt($session, CURLOPT_FILE, $logfh);curl_setopt($session, CURLOPT_VERBOSE, true);curl_exec($session);curl_close($session);fclose($logfh);


There could be also issue while using CURLINFO_HEADER_OUT = true. I guess there is something in CURLINFO_VERBOSE that uses this option and just supress VERBOSE information...

curl_setopt($ch, CURLINFO_HEADER_OUT, false);curl_setopt($ch, CURLOPT_VERBOSE, true);curl_setopt($ch, CURLOPT_STDERR, fopen('log.log', 'a+'));

Just to mention, you can use:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_VERBOSE, true);curl_setopt($ch, CURLOPT_STDERR, fopen('log.log', 'a+'));

If you want to log output to file and still be able to return curl_exec.