Curl outputting to screen or not saving as file

159
May 19, 2018, at 1:50 PM

I have the following code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sourceURL);
curl_setopt($ch, CURLOPT_FILE, $dl_destination);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlResult = curl_exec($ch);
$cError = curl_error($ch);
curl_close($ch);

This seems to work fine in one location in the script but not another. In the problem area it will output the file contents to the screen and save the file. Without CURLOPT_RETURNTRANSFER it will save the file and output the contents to the screen. If add CURLOPT_RETURNTRANSFER as I've read should work, it does not save the file and instead puts the contents into $curlResult. I just need it to save the file without outputting to the screen.

Answer 1

Fetch the data using CURLOPT_RETURNTRANSFER and save it in a variable. Now, use file_put_contents to write data to a file.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sourceURL);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlResult = curl_exec($ch);
$cError = curl_error($ch);
curl_close($ch);
if(empty($cError)){
    if(file_put_contents($dl_destination,$curlResult)){
        echo "Data written to file successfully";
    }else{
        die("Could not write to file.");
    }
}else{
    die("Curl Error: " .$cError);
}
Rent Charter Buses Company
READ ALSO
Composer (Phar error) with Php 7.1.17

Composer (Phar error) with Php 7.1.17

When I run the command: composer install

324
PDOStatement::fetch occasionally returns false, but errorInfo() is empty

PDOStatement::fetch occasionally returns false, but errorInfo() is empty

I am having strange problem with PDOCode is like this:

170
nginx + php-fpm70 getting 502 bad gateway

nginx + php-fpm70 getting 502 bad gateway

I'm Getting 502 bad gateway error in one of my magento2 site

216