Using WordPress ‘download_url()’ PHP function

The download_url() WordPress PHP function is used to download a URL to a local temporary file using the WordPress HTTP API. After downloading, the calling function must unlink() the file.

Usage

For instance, if you wanted to download a file from a given URL to a temporary location on your WordPress server:

// The URL of the file you want to download
$file_url = 'https://example.com/myfile.ext';

// Use the function to download the file to a temporary location
$tmp_file = download_url( $file_url );

// Set the final destination for the file.
$filepath = ABSPATH . 'wp-content/uploads/myfile.ext';

// Copy the file to the final destination and delete the temporary file.
copy( $tmp_file, $filepath );
@unlink( $tmp_file );

Parameters

  • $url (string) – Required. The URL of the file to download.
  • $timeout (int) – Optional. The timeout for the request to download the file. Default is 300 seconds.
  • $signature_verification (bool) – Optional. Whether to perform Signature Verification. Default is false.

More information

See WordPress Developer Resources: download_url()
This function can be used in the front-end or cron, but you must include wp-admin/includes/file.php file.

Examples

Basic File Download

In this example, we’re downloading a file from a specific URL and saving it in our WordPress uploads directory.

$file_url = 'https://example.com/myfile.pdf';
$tmp_file = download_url( $file_url );
$filepath = ABSPATH . 'wp-content/uploads/myfile.pdf';
copy( $tmp_file, $filepath );
@unlink( $tmp_file );

Download with Timeout

This example shows how to set a custom timeout for the download request.

$file_url = 'https://example.com/bigfile.zip';
$timeout = 600; // set timeout to 600 seconds
$tmp_file = download_url( $file_url, $timeout );
$filepath = ABSPATH . 'wp-content/uploads/bigfile.zip';
copy( $tmp_file, $filepath );
@unlink( $tmp_file );

Download with Signature Verification

This example shows how to enable signature verification for the download.

$file_url = 'https://example.com/securefile.zip';
$signature_verification = true; // enable signature verification
$tmp_file = download_url( $file_url, 300, $signature_verification );
$filepath = ABSPATH . 'wp-content/uploads/securefile.zip';
copy( $tmp_file, $filepath );
@unlink( $tmp_file );

Download Multiple Files

This example shows how to download multiple files.

$urls = ['https://example.com/file1.zip', 'https://example.com/file2.zip'];
foreach($urls as $url) {
    $tmp_file = download_url( $url );
    $filepath = ABSPATH . 'wp-content/uploads/' . basename($url);
    copy( $tmp_file, $filepath );
    @unlink( $tmp_file );
}