download_url

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

Description

download_url( (string) $url, (int) $timeout = 300 ); 

Please note, That the calling function must unlink() the file.

Parameters (2)

0. $url (string)
The URL of the file to download
1. $timeout — Optional. (int) => 300
The timeout for the request to download the file default 300 seconds

Usage

  1. if ( !function_exists( 'download_url' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/file.php'; 
  3.  
  4. // the URL of the file to download 
  5. $url = ''; 
  6.  
  7. // The timeout for the request to download the file default 300 seconds 
  8. $timeout = 300; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = download_url($url, $timeout); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/file.php  
  1. function download_url( $url, $timeout = 300 ) { 
  2. //WARNING: The file is not automatically deleted, The script must unlink() the file. 
  3. if ( ! $url ) 
  4. return new WP_Error('http_no_url', __('Invalid URL Provided.')); 
  5.  
  6. $url_filename = basename( parse_url( $url, PHP_URL_PATH ) ); 
  7.  
  8. $tmpfname = wp_tempnam( $url_filename ); 
  9. if ( ! $tmpfname ) 
  10. return new WP_Error('http_no_file', __('Could not create Temporary file.')); 
  11.  
  12. $response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) ); 
  13.  
  14. if ( is_wp_error( $response ) ) { 
  15. unlink( $tmpfname ); 
  16. return $response; 
  17.  
  18. if ( 200 != wp_remote_retrieve_response_code( $response ) ) { 
  19. unlink( $tmpfname ); 
  20. return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) ); 
  21.  
  22. $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' ); 
  23. if ( $content_md5 ) { 
  24. $md5_check = verify_file_md5( $tmpfname, $content_md5 ); 
  25. if ( is_wp_error( $md5_check ) ) { 
  26. unlink( $tmpfname ); 
  27. return $md5_check; 
  28.  
  29. return $tmpfname;