In this tutorial I will explain you how to download file from URL. We two methods to get content from external URL’s, file_get_contents and CURL.
Using file_get_contents : This function reads entire file into a string. But this function only works when fopen is enabled.
$fileUrl = 'http://www.gettyimages.in/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg'; $fileExt = substr(strrchr($fileUrl,'.'),1); $fileNewName = 'files/'.time().".".$fileExt; $fp = fopen($fileNewName, 'wb'); $content = file_get_contents($fileUrl); fwrite($fp, $content); fclose($fp);
Using CURL : CURL supports http, https, ftp, file protocols and more. Mostly enabled on all server these days.
$fileUrl = 'http://www.gettyimages.in/gi-resources/images/Homepage/Hero/UK/CMS_Creative_164657191_Kingfisher.jpg'; $fileExt = substr(strrchr($fileUrl,'.'),1); $fileNewName = 'files/'.time().".".$fileExt; $ch = curl_init($fileUrl); $fp = fopen($fileNewName, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp);
If you are using https url and you don’t have SSL certificate file then you can add following lines with CURL:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
You can use any of the above methods to download file from url. CURL is mostly used method these days, so I prefer CURL. fopen function with ‘wb’ is used to create a file for writing.
Hope this will help you to download file from URL.