Download a remote file with php

There are many methods in PHP to download the remote file.I am going to explain few methods which are the best and easy to implement.

1-Using CURL(Client URL):-Curl is the best method to download a remote file because curl provides many options to handle your download.Here is the few things which makes it the best.

You can send and receive the cookies using curl.

You can read the headers of remote file without downloading it.

You can handle the redirection of URL.

Curl uses the gzip compression so it makes the file transfer faster.

Here is an example code to download the remote file using curl-

Download a remote file using Curl

PHP

1

2

3

4

5

6

7

8

9

<?php

$url='http://www.example.com/file.zip';// address of remote file

$path='/folder/filename.zip';//address of local file

$ch=curl_init($url);

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

$con=curl_exec($ch);

curl_close($ch);

file_put_contents($path,$con);

?>

In the above example i have used CURLOPT_RETURNTRANSFER option to prevent the server to send the output to the client’s browser.A disadvantage of this method is that it stores the partially downloaded file into memory until the download is completed.If the file is huge(say >20MB) then it may exceed the memory limit,so if you are going to use this method to download this file then better to use the following code-

Download large file using curl

PHP

1

2

3

4

5

6

7

8

9

10

<?php

$url='http://www.example.com/file.zip';//address of remote file

$path='/folder/file.zip';//path of local file

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

$ch=curl_init($url);

curl_setopt($ch,CURLOPT_FILE,$fp);

$data=curl_exec($ch);

curl_close($ch);

fclose($fp);

?>

In the above example the script is writing a file into local file instead of saving it to memory.So if the file size is huge you dont need to worry about PHP’s exceed memory limit.

2-Using file_get_contents()– It is the library function of PHP to download the remote file.It is very simple to use and doesn’t support too many options like curl.The example code is given below-