14

How can I save a file using curl and PHP?

2
  • 3
    are you sure you need curl? is file_get_contents("whatever.com") not enough? Commented Jun 17, 2009 at 12:12
  • 2
    I'm sure over 50% of the 14,000 views did not find that file_get_contents was enough Commented Mar 13, 2015 at 21:53

3 Answers 3

40

did you want something like this ?

function get_file($file, $local_path, $newfilename) 
{ 
    $err_msg = ''; 
    echo "<br>Attempting message download for $file<br>"; 
    $out = fopen($local_path.$newfilename,"wb");
    if ($out == FALSE){ 
      print "File not opened<br>"; 
      exit; 
    } 

    $ch = curl_init(); 

    curl_setopt($ch, CURLOPT_FILE, $out); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_setopt($ch, CURLOPT_URL, $file); 

    curl_exec($ch); 
    echo "<br>Error is : ".curl_error ( $ch); 

    curl_close($ch); 
    //fclose($handle); 

}//end function 

Functionality: Its a function and accepts three parameters

get_file($file, $local_path, $newfilename)

$file : is the filename of the object to be retrieved

$local_path : is the local path to the directory to store the object

$newfilename : is the new file name on the local system

Sign up to request clarification or add additional context in comments.

Comments

14

You can use:

<?php
// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HEADER, 0);

// grab URL and pass it to the browser
$out = curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);


$fp = fopen('data.txt', 'w');
fwrite($fp, $out);
fclose($fp);

?>

See: https://www.php.net/manual/en/function.curl-exec.php and https://www.php.net/manual/en/function.fwrite.php

3 Comments

This will do the job for small files, but it loads the entire file into memory before saving, and so you will probably hit fatal 'out of memory' errors if the file is larger than PHP's memory limit. Haim Evgi's answer correctly streams the file to disk which avoids this issue.
I curl_exec straight into file_put_contents(). At the least, it saves 3 lines of code.
As in this example, CURLOPT_RETURNTRANSFER is set before CURLOPT_FILE. The order of the CURLOPT_* is significant (see php.net/manual/en/function.curl-setopt.php#99082).
-6

I think curl has -o option to write the output to a file instead of stdout.

After -o you have to provide the name of the output file.

example:

curl -o path_to_the_file url

1 Comment

This is for the command-line version of curl, but not the PHP curl library.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.