How to download a file using Curl in PHP – Code Snippet

By | January 13, 2023

Download a File using Curl

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.

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

One Comment

How to download a file using Curl in PHP – Code Snippet
  1. RaminFaizy

    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 Reply

Your email address will not be published. Required fields are marked *