How to download files directly on server via PHP

You can use following function to save any type of file on server/directory

function downloadUrlToFile($url, $outFileName)
{   
    if(is_file($url)) {
        copy($url, $outFileName); 
    } else {
        $options = array(
          CURLOPT_FILE    => fopen($outFileName, 'w'),
          CURLOPT_TIMEOUT =>  28800, // set this to 8 hours so we dont timeout on big files
          CURLOPT_URL     => $url
        );

        $ch = curl_init();
        curl_setopt_array($ch, $options);
        curl_exec($ch);
        curl_close($ch);
    }
}

To download large files you can set following code in top:

ignore_user_abort(true); // Script will run in background even if you will close the browser
set_time_limit(0); // Set execution time unlimited

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.