I'm trying to log the information from a cURL hit into a log file but am unable to do so, I run windows with wamp and have given full control to all users in the machine and the log and php file that invokes cURL are in same directory for this test. I've used the below code:
$session = curl_init();
$logfh = fopen("my_log.log", 'a+');
if ($logfh) {
print "Opened the log file without errors";
}
curl_setopt($session, CURLOPT_HEADER, false);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
// Optional settings for debugging
curl_setopt($session, CURLOPT_VERBOSE, true);
curl_setopt($session, CURLOPT_FILE, $logfh); // logs curl messages
// curl_setopt($session, CURLOPT_STDERR, $logfh); // logs curl messages
curl_exec($session);
curl_close($session);
The log file opens without error and my cURL returns success but nothing is logged into the file.I've used CURLOPT_FILE
and CURLOPT_STDERR
alternatively but neither help the cause and not sure if i got something wrong here. Any suggestions on debugging this would be appreciated.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With