Php remotely obtains the file content and downloads it to the local device. Note: This demo applies to the yii Framework. if you are not using the yii Framework, this method also applies to you and provides a brief understanding of the concept.
/*** Save the file locally * @ param file path $ url * @ param save local path $ savePath * @ return string */public static function downloadFile ($ url) {$ www_root = Yii: getPathOfAlias ('webroot'); $ root_dir = 'uploads/audio '; $ build_dir = date ('Y '). '/'. date ('M'); $ origin_dir = $ root_dir. '/'. $ build_dir; $ savePath = $ www_root. DIRECTORY_SEPARATOR. $ origin_dir. DIRECTORY_SEPARATOR; // local storage path (by year, month, or day) $ fileName = Comm On: getUrlFileExt ($ url); // get the file extension if (! File_exists ($ savePath) {Common: mkdirs ($ savePath); // The directory does not exist.} $ fileName = time (). '. '. $ fileName; // $ file = file_get_contents ($ url); $ ch = curl_init (); $ timeout = 60; curl_setopt ($ ch, CURLOPT_URL, $ url ); curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt ($ ch, CURLOPT_CONNECTTIMEOUT, $ timeout); $ file_contents = curl_exec ($ ch); curl_close ($ ch ); // use curl $ ch to stream the returned file if (! Empty ($ file_contents) {file_put_contents ($ savePath. '/'. $ fileName, $ file_contents); // return '/' to the local address '/'. $ origin_dir. '/'. $ fileName; // return Local Address}/*** get file extension * @ param webpage URL $ url * @ return string */public static function getUrlFileExt ($ url) {$ ary = parse_url ($ url); $ file = basename ($ ary ['path']); $ ext = explode ('. ', $ file); return $ ext [1];}
/*** Create a multilevel directory */public static function mkdirs ($ dir) {if (! Is_dir ($ dir) {if (! Common: mkdirs (dirname ($ dir) {return false;} if (! Mkdir ($ dir, 0777) {return false;} return true ;}
DownloadFile (#); // call
The above is the detailed description of the sample code for php to download far beyond the local file. For more information, see other related articles in the first PHP community!