Wednesday 8 August 2018

Downloading Files With CURL In PHP

This is a simple tutorial on how to download files with cURL in PHP.
Firstly, allow me to present you with the code (because let’s be honest, that’s what most of you came here for). The example below will download a fictional logo image via cURL. Simply change the $fileUrl and $saveTo variables to meet your requirements.
Now for the explanation!
To download a file via cURL, we need to give it a file pointer resource. We can achieve this by using the fopen function like so:
On success, the fopen function will return a file pointer resource. Note that we pass in “w+” as the second parameter because “w+” tells PHP that we want to open the file for reading and writing.
After we’ve successfully set up our file pointer, we can hand it over to cURL via the CURLOPT_FILE option, like so:
This tells cURL that we want to save the transferred data of our request to the given file. Note that we also set the option CURLOPT_TIMEOUT to 20 seconds, simply because larger file sizes may result in longer request (when it comes to downloading files, we need to be weary of the possibility of timeouts):
As you can see, downloading a resource with cURL in PHP is not much different than sending a regular HTTP request. The only difference is that you need to give cURL a valid stream resource.

0 comments:

Post a Comment