(Linux CLI PHP) Capturing the correct CURL output to a file at runtime

I just noticed that if you run a php script command line that uses curl with the CURLOPT_VERBOSE parameter, you cannot capture the output ...

Example:

$php myscript.php > logfile.txt 2>&1

All PHP output will go into the log file, but the failure will still hit the screen.

How can I capture PHP output with curl output?

    $ch = curl_init();  // Initialising cURL
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    curl_setopt($ch, CURLOPT_USERAGENT, $this->agentString);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_URL, $url);    
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $data = curl_exec($ch); 
    curl_close($ch);

Edit:

Adding a line

curl_setopt($ch, CURLOPT_STDERR, STDOUT);

This seems to be a trick. However, now it seems that the output of curl conflicts with the output of php and overwrites the log file with its own output. Weird!

Edit 2:

It works

 $php myscript.php >> logfile.txt 2>&1
+4
source share
3 answers

Actually, my first answer is wrong. The cURL man page says:

URLOPT_VERBOSE . STDERR , CURLOPT_STDERR.

, STDOUT CURLOPT_STDERR:

curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, STDOUT);

:

, CURLOPT_RETURNTRANSFER.

+2

, , . , .

ob_start()

$ch = curl_init();  // Initialising cURL
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $this->agentString);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL, $url);    
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$data = curl_exec($ch); 
curl_close($ch);

// What ever other functions you want run...

// discard content: ob_end_clean()
$extra_curl_stuff = ob_get_flush();
// save $extra_curl_stuff to your logfile too...
0

If you are looking for a solution for PHP, you can use the CURL options:

...
// this returns the data instead of outputing it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// output the data
echo curl_exec($ch);

Or you can buffer and output the output:

// turn on output buffering
ob_start();

// do some curl operations here

// flush and turn off buffering
ob_end_flush();
-1
source

All Articles