Search code examples
phpcurlfopenfclose

PHP Download file to server


I am trying to download images using curl from php, however instead of saving the image to the server it is just outputting random characters to the web browser screen, here's the code

$final['IMAGE'] = 'http://www.google.com/images/srpr/logo3w.png';

$imagename = trim(basename($final['IMAGE']));

$url  = $final['IMAGE'];
$path = '/media/import/';
$path .= $imagename;

$fp = fopen($path, 'w');

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);

$data = curl_exec($ch);

curl_close($ch);
fclose($fp);

Solution

  • curl_exec($ch); will print the output directly to the screen. You can stop his behavior when using the CURLOPT_RETURNTRANSFER-option:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    

    See the PHP-manual "curl_setopt" for more information.

    Edit

    This little script downloads the file to a writable directory:

    // file handler
    $file = fopen(dirname(__FILE__) . '/test.png', 'w');
    // cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,'somethinsomething.com/something.png');
    // set cURL options
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // set file handler option
    curl_setopt($ch, CURLOPT_FILE, $file);
    // execute cURL
    curl_exec($ch);
    // close cURL
    curl_close($ch);
    // close file
    fclose($file);
    

    This time it's the CURLOPT_FILE-option that does the trick. More information can be found on the same link as before.