Skip to main content

Download File from Remote Server with PHP CURL

On my previous post I was shown how we can get a remote file size without download it in php. Today I am going to show you how can we download a file from remote server with php.

There are many ways in PHP to download file from remote server. We can use php functions like copy, file_get_content, fopen, fsockopen to download remote files. These functions are well but today we will use curl to download file. Because it the advanced way to working with remote resources.We can download large file with minimum memory usages in this way.

getHeaders Function

This function gets all header information before downloading a file. This function will help you to know file is exist or not and filesize

/**
 * Get Headers function
 * @param str #url
 * @return array
 */
function getHeaders($url)
{
  $ch = curl_init($url);
  curl_setopt( $ch, CURLOPT_NOBODY, true );
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_HEADER, false );
  curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
  curl_setopt( $ch, CURLOPT_MAXREDIRS, 3 );
  curl_exec( $ch );
  $headers = curl_getinfo( $ch );
  curl_close( $ch );

  return $headers;
}

download Function

This function download file form remote server.

/**
 * Download
 * @param str $url, $path
 * @return bool || void
 */
function download($url, $path)
{
  # open file to write
  $fp = fopen ($path, 'w+');
  # start curl
  $ch = curl_init();
  curl_setopt( $ch, CURLOPT_URL, $url );
  # set return transfer to false
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, false );
  curl_setopt( $ch, CURLOPT_BINARYTRANSFER, true );
  curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
  # increase timeout to download big file
  curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, 10 );
  # write data to local file
  curl_setopt( $ch, CURLOPT_FILE, $fp );
  # execute curl
  curl_exec( $ch );
  # close curl
  curl_close( $ch );
  # close local file
  fclose( $fp );

  if (filesize($path) > 0) return true;
}

Usages

$url = 'http://path/to/remote/file.jpg';
$path = 'uploads/file.jpg';

$headers = getHeaders($url);

if ($headers['http_code'] === 200 and $headers['download_content_length'] < 1024*1024) {
  if (download($url, $path)){
    echo 'Download complete!'; 
  }
}

Comments

  1. I'm getting a 403 return, what to do?

    ReplyDelete
  2. If I want to copy multiple files at the same time..

    ReplyDelete
  3. Thank for this nice and functional code!

    ReplyDelete
  4. how to download a file of 1.5 gb in size directly to server. it says after some 100 mb connection timeout.

    ReplyDelete
  5. Really nice code !
    I have one question : if you want to download from HTTPs, how could you do ?
    When I put curl_setopt($ch, CURLOPT_SSLVERSION,3); I have
    SSL certificate problem: unable to get local issuer certificate

    Thanks.

    ReplyDelete
  6. Hello Admin, thank you for enlightening us with your knowledge sharing. PHP has become an inevitable part of web development, and with proper PHP training in Chennai, one can have a strong career in the web development field. We from Fita provide PHP course in Chennai with the best facilitation. Any aspiring students can join us for the best PHP training institute in Chennai.

    ReplyDelete
  7. Perfecto. Excelente aporte. No habia tenido la oportunidad de usar curl y me funciono excelente a la primera trabajarlo para varias imagenes en DOM. Gracias.

    ReplyDelete
  8. That all I need for my download script by using PHP. Thanks for your tut!
    You can visit http://f5movies.top in free time to relax :)

    ReplyDelete
  9. it get error: Fatal error: Call to undefined function getHeaders() in xml/wget.php on line 6

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. https://xemphim7.com thanks for share

    ReplyDelete
  12. Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.

    ReplyDelete
  13. Thank you very much, this worked well when fopen was not working for me.

    ReplyDelete
  14. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here. php training in chennai

    ReplyDelete
  15. It is a very nice article including a lot of viral content. I am going to share it on social media. Get the Cold Pressed Oil

    ReplyDelete
  16. It's great that you are telling us about these things. Jade

    ReplyDelete
  17. Awesome blog. Your articles really impressed for me, because of all information so nice and unique...
    Best cloud Computing Training Institute in Chennai | Best cloud Computing Training Institute in Velachery

    ReplyDelete
  18. I am reading your post from the beginning, it was so interesting to read & I feel thanks to you for posting such a good blog, keep updates regularly.
    Best Automation Anywhere Training Institute in Chennai | Best Automation Anywhere Training Institute in Kanchipuram

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.