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);

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
Back to blog

Leave a comment

Please note, comments need to be approved before they are published.