/** * Downloads the file from remote server to specified location on local server. Uses regular file operations or cURL or sockets (whichever available first) to download the file. * * @param url $source_url url of the source file * @param string $target_folder target folder name, should end with DS * @param string $target_file target file name. */ public static function download_file($source_url, $target_folder, $target_file) { if (file_exists($target_file)) { JFile::delete($target_file); } else { JFolder::create($target_folder); } //try to connect via fopen if (function_exists('fopen') && ini_get('allow_url_fopen')) { //set socket timeout ini_set('default_socket_timeout', 5); $handle = fopen($source_url, 'rb'); if ($handle) { $download = fopen($target_folder . $target_file, "wb"); if ($download) { while (!feof($handle)) { fwrite($download, fread($handle, 1024 * 8), 1024 * 8); } } } if ($handle) { fclose($handle); } } else { if (function_exists('curl_init') && function_exists('curl_exec')) { $fh = fopen($target_folder . $target_file, "w"); $options = array(CURLOPT_FILE => $fh, CURLOPT_URL => $source_url, CURLOPT_TIMEOUT => 28800, CURLOPT_FAILONERROR => 1, CURLOPT_HEADER => 0, CURLOPT_TIMEOUT => 5); $ch = curl_init(); curl_setopt_array($ch, $options); curl_exec($ch); curl_close($ch); fclose($fh); } else { if (function_exists('fsockopen') && $data == '') { $errno = 0; $errstr = ''; $parts = JString::parse_url($source_url); $hostname = $parts['host']; unset($parts['scheme']); unset($parts['host']); $filename = CJFunctions::join_url($parts); //timeout handling: 5s for the socket and 5s for the stream = 10s $fsock = fsockopen($hostname, 80, $errno, $errstr, 5); if ($fsock) { fputs($fsock, 'GET ' . $filename . ' HTTP/1.1\\r\\n'); fputs($fsock, 'HOST: ' . $hostname . '\\r\\n'); fputs($fsock, 'Connection: close\\r\\n\\r\\n'); //force stream timeout... stream_set_blocking($fsock, 1); stream_set_timeout($fsock, 5); $get_info = false; $download = fopen($target_folder . $target_file, 'wb'); while (!feof($fsock)) { if ($get_info) { fwrite($download, fread($handle, 1024 * 8), 1024 * 8); } else { if (fgets($fsock, 8192) == '\\r\\n') { $get_info = true; } } } fclose($fsock); } } } } }