Download a file using curl in php

Here is a quick curl snippet for php, that can download a remote file and save it.

<?php

set_time_limit(0);

//File to save the contents to
$fp = fopen ('files2.tar', 'w+');

$url = "http://localhost/files.tar";

//Here is the file we are downloading, replace spaces with %20
$ch = curl_init(str_replace(" ","%20",$url));

curl_setopt($ch, CURLOPT_TIMEOUT, 50);

//give curl the file pointer so that it can write to it
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$data = curl_exec($ch);//get curl response

//done
curl_close($ch);

The CURLOPT_FILE option takes a file resources and writes the content of the url to that file resource/handle. Also set the script time limit to something large so that the script does not end when downloading large files.






Last Updated On : 19th March 2013

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at [email protected]. Or find him on

1 Comment + Add Comment

  • hello sire i see this error while upload file from remote server the file is uploading complete but i see this error:
    Network Error (tcp_error)

    A communication error occurred: “”

    The Web Server may be down, too busy, or experiencing other problems
    preventing it from responding to requests. You may wish to try again at a
    later time.

    For assistance, contact your network support team.

    my email is [email protected]

Leave a comment



Connect with us