You think of using php for downloading files from URL is an easy task ?. If yes, you are absolutely correct it’s really easy to download files from URL in php.
Firstly I will tell you a quick way how to do it so that if you are working on some important stuff you won’t waste much time.
Table Of Contents
Download A File From URL Using PHP With file_get_contents
Probably this is the easiest way to download a file from URL. We just need to use the functions file_get_contents and file_put_contents for grabbing the data and then putting it into a file.
It can be done like this –
$url = "https://example.com/file-to-download.zip" ; // URL of the file you want to download $filename = basename($url); // Getting the base name of the file. file_put_contents($filename,file_get_contents($url));
This thing is gonna work for most of you.
Using PHP cURL To Download File From URL
Now we will see how to use php curl to download file from URL. It’s simple we just need to initialize cURL then grab the data and save it into a file.
You can use cURL like this –
$url = "https://example.com/file-to-download.zip" ; $ch = curl_init($url); $my_save_dir = './'; $filename = basename($url); $complete_save_loc = $my_save_dir . $filename; $fp = fopen($complete_save_loc, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
file_get_contents vs cURL ? What Should you use.
Do you think that both file_get_contents and curl do the same thing then you might be wrong. both of them look similar but are not the same. it’s like you can use both of them but choosing the php cURL over file_get_contents could be a good choice.
if you just want to download a handful of files to download file_get_contents might work for you. But if you have a large number URLs to download files from then using php cURL can help you save some time. It will also be handy if you need the header, HTTP request method, timeout, cookiejar, redirects, etc.
Therefore if you have a large number of files to download with php I would recommend you to use cURL and yes you can also read more about curl over here.
And in case if you mess up with the filenames you can use the php rename function.