Download file with cURL – PHP Tutorial
Download file with cURL – PHP Tutorial
Article by Rey Calantaol
In this tutorial I will show you how to download files from remote server using PHP’s libcURL(cURL) functionality. libcURL is the most widely used PHP library in downloading and uploading files over the net.Before going further let us go back first on when libcURL have been included in the PHP library.According the php.net manual, libcURL was added since the released of PHP v4.0.2. It is a library added to PHP to allow us to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
The following example show how to download file from remote server:
$ file = “http://domain.com/directory/filename”; $ save_path = ‘download/’; $ fp = fopen($ save_path.basename($ file), ‘w’); $ ch = curl_init($ url); curl_setopt($ ch, CURLOPT_FILE, $ fp); $ data = curl_exec($ ch); curl_close($ ch); fclose($ fp);
This is example is very straightforward, first $ file variable was assigned with the URL path of the remote file, that is the address that points directly to the file to be downloaded, second we created the local file with the same name with the remote file.Third initiate curl handle and setting appropriate curl options. Lastly, execute the command and close curl handle and the file pointer.
How about those password protected files?Sometimes we were dealing with password protected files from the remote server. With this, we don’t have worries because cURL supports user authentication while connecting to the remote host.To accomplish this, we will just set additional option in the curl_opt parameter. It look like below:curl_setopt($ ch, CURLOPT_USERPWD, “username:password”);br /> curl_setopt($ ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
So, combining the code with the previous one we have it like this:
$ file = “http://domain.com/directory/filename”;$ save_path = ‘download/’;$ fp = fopen($ save_path.basename($ file), ‘w’); $ ch = curl_init($ url);curl_setopt($ ch, CURLOPT_USERPWD, “username:password”);curl_setopt($ ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);curl_setopt($ ch, CURLOPT_FILE, $ fp); $ data = curl_exec($ ch); curl_close($ ch);fclose($ fp);
That’s it, it save a lot of time.
Source: http://reygcalantaol.com/2011/07/13/download-file-from-remote-host-with-curl/
About the Author
Rey is a webpage developer and a freelance bloggerhttp://reygcalantaol.com
