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.

  1. You can send and receive the cookies using curl.
  2. You can read the headers of  remote file without downloading it.
  3. You can handle the redirection of  URL.
  4. Curl uses the gzip compression so it makes the file transfer faster.

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

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-

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-

 

 

  • syntrax

    The possibilities are endless ! Thx for the tut