download_url

Definition:
function download_url( $url, $timeout = 300 ) {}

Downloads a url to a local temporary file using the WordPress HTTP Class.
Please note, That the calling function must unlink() the file.

Parameters

  • string $url: the URL of the file to download
  • int $timeout: The timeout for the request to download the file default 300 seconds

Return values

returns:WP_Error on failure, string Filename on success.

Source code

function download_url( $url, $timeout = 300 ) {

	//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.'));



	$tmpfname = wp_tempnam($url);

	if ( ! $tmpfname )

		return new WP_Error('http_no_file', __('Could not create Temporary file.'));



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



	if ( is_wp_error( $response ) ) {

		unlink( $tmpfname );

		return $response;

	}



	if ( 200 != wp_remote_retrieve_response_code( $response ) ){

		unlink( $tmpfname );

		return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );

	}



	return $tmpfname;

}

940

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: