Random WordPress Function

Learn about a new WordPress function every day!


Function Signature:

download_url

Function Description:

Downloads a URL to a local temporary file using the WordPress HTTP API.

Function Examples:

⚠️ Examples below are generated with GPT-3 once every hour. Do not take them too seriously.
Consider them as some extra input in your learning process - reason about them. Will it work? What could fail?
// Example 1: Download a file from a given URL and save it to the uploads directory
$file_url = 'https://example.com/file.zip';
$upload_dir = wp_upload_dir();
$downloaded_file = download_url( $file_url, 300 );
if( is_wp_error( $downloaded_file ) ){
    // Handle error
} else {
    $file_name = basename( $file_url );
    $file_path = $upload_dir['path'] . '/' . $file_name;
    $file = file_put_contents( $file_path, file_get_contents( $downloaded_file ) );
    if( $file ){
        // File downloaded successfully
    } else {
        // Handle error
    }
}
// Example 2: Download a file from a URL with custom timeout and verify SSL certificate
$file_url = 'https://example.com/file.zip';
$downloaded_file = download_url( $file_url, 60, array( 'timeout' => 30, 'sslverify' => true ) );
if( is_wp_error( $downloaded_file ) ){
    // Handle error
} else {
    // File downloaded successfully
}
// Example 3: Handle a large file download by setting the stream flag to true
$file_url = 'https://example.com/largefile.zip';
$downloaded_file = download_url( $file_url, 300, array( 'stream' => true ) );
if( is_wp_error( $downloaded_file ) ){
    // Handle error
} else {
    // File downloaded successfully
}