download_url( string $url, int $timeout = 300, bool $signature_verification = false )

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


Description Description

Please note that the calling function must unlink() the file.


Parameters Parameters

$url

(string) (Required) The URL of the file to download.

$timeout

(int) (Optional) The timeout for the request to download the file. Default 300 seconds.

Default value: 300

$signature_verification

(bool) (Optional) Whether to perform Signature Verification.

Default value: false


Top ↑

Return Return

(string|WP_Error) Filename on success, WP_Error on failure.


Top ↑

Source Source

File: wp-admin/includes/file.php

function download_url( $url, $timeout = 300, $signature_verification = false ) {
	//WARNING: The file is not automatically deleted, The script must unlink() the file.
	if ( ! $url ) {
		return new WP_Error( 'http_no_url', __( 'Invalid URL Provided.' ) );
	}

	$url_filename = basename( parse_url( $url, PHP_URL_PATH ) );

	$tmpfname = wp_tempnam( $url_filename );
	if ( ! $tmpfname ) {
		return new WP_Error( 'http_no_file', __( 'Could not create Temporary file.' ) );
	}

	$response = wp_safe_remote_get(
		$url,
		array(
			'timeout'  => $timeout,
			'stream'   => true,
			'filename' => $tmpfname,
		)
	);

	if ( is_wp_error( $response ) ) {
		unlink( $tmpfname );
		return $response;
	}

	$response_code = wp_remote_retrieve_response_code( $response );

	if ( 200 != $response_code ) {
		$data = array(
			'code' => $response_code,
		);

		// Retrieve a sample of the response body for debugging purposes.
		$tmpf = fopen( $tmpfname, 'rb' );
		if ( $tmpf ) {
			/**
			 * Filters the maximum error response body size in `download_url()`.
			 *
			 * @since 5.1.0
			 *
			 * @see download_url()
			 *
			 * @param int $size The maximum error response body size. Default 1 KB.
			 */
			$response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
			$data['body']  = fread( $tmpf, $response_size );
			fclose( $tmpf );
		}

		unlink( $tmpfname );
		return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
	}

	$content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
	if ( $content_md5 ) {
		$md5_check = verify_file_md5( $tmpfname, $content_md5 );
		if ( is_wp_error( $md5_check ) ) {
			unlink( $tmpfname );
			return $md5_check;
		}
	}

	// If the caller expects signature verification to occur, check to see if this URL supports it.
	if ( $signature_verification ) {
		/**
		 * Filters the list of hosts which should have Signature Verification attempteds on.
		 *
		 * @since 5.2.0
		 *
		 * @param array List of hostnames.
		 */
		$signed_hostnames       = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) );
		$signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
	}

	// Perform signature valiation if supported.
	if ( $signature_verification ) {
		$signature = wp_remote_retrieve_header( $response, 'x-content-signature' );
		if ( ! $signature ) {
			// Retrieve signatures from a file if the header wasn't included.
			// WordPress.org stores signatures at $package_url.sig

			$signature_url = false;
			$url_path      = parse_url( $url, PHP_URL_PATH );
			if ( substr( $url_path, -4 ) == '.zip' || substr( $url_path, -7 ) == '.tar.gz' ) {
				$signature_url = str_replace( $url_path, $url_path . '.sig', $url );
			}

			/**
			 * Filter the URL where the signature for a file is located.
			 *
			 * @since 5.2.0
			 *
			 * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known.
			 * @param string $url                 The URL being verified.
			 */
			$signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );

			if ( $signature_url ) {
				$signature_request = wp_safe_remote_get(
					$signature_url,
					array(
						'limit_response_size' => 10 * 1024, // 10KB should be large enough for quite a few signatures.
					)
				);

				if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
					$signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) );
				}
			}
		}

		// Perform the checks.
		$signature_verification = verify_file_signature( $tmpfname, $signature, basename( parse_url( $url, PHP_URL_PATH ) ) );
	}

	if ( is_wp_error( $signature_verification ) ) {
		if (
			/**
			 * Filters whether Signature Verification failures should be allowed to soft fail.
			 *
			 * WARNING: This may be removed from a future release.
			 *
			 * @since 5.2.0
			 *
			 * @param bool   $signature_softfail If a softfail is allowed.
			 * @param string $url                The url being accessed.
			 */
			apply_filters( 'wp_signature_softfail', true, $url )
		) {
			$signature_verification->add_data( $tmpfname, 'softfail-filename' );
		} else {
			// Hard-fail.
			unlink( $tmpfname );
		}

		return $signature_verification;
	}

	return $tmpfname;
}

Top ↑

Changelog Changelog

Changelog
Version Description
5.2.0 Signature Verification with SoftFail was added.
2.5.0 Introduced.


Top ↑

User Contributed Notes User Contributed Notes

  1. Skip to note 1 content
    Contributed by Breno Alves

    To be able to use this function in the front-end nor cron you must include wp-admin/includes/file.php file.

    <?php
    
    // If the function it's not available, require it.
    if ( ! function_exists( 'download_url' ) ) {
    	require_once ABSPATH . 'wp-admin/includes/file.php';
    }
    
    // Now you can use it!
    $file_url = 'https://example.com/myfile.ext';
    $tmp_file = download_url( $file_url );
    
    // Sets file final destination.
    $filepath = ABSPATH . 'wp-content/uploads/myfile.ext';
    
    // Copies the file to the final destination and deletes temporary file.
    copy( $tmp_file, $filepath );
    @unlink( $tmp_file );
    
    
  2. Skip to note 2 content
    Contributed by Marcio Zebedeu

    WordPress files can be called easily by accessing the wp-load file.php which is located at the root of wordpress installation.

        require_once(BASE_PATH . 'wp-load.php');
    
    
        /*
            link to file to be downloaded
        */
    	    public function download( $url = "http://www.example.com/example/downloads/information/php.pdf"){
            download_url( $url );
    }
    

You must log in before being able to contribute a note or feedback.