wp_handle_upload()WP 2.0.0

Wrapper for _wp_handle_upload().

Passes the wp_handle_upload action.

No Hooks.

Return

Array. See _wp_handle_upload() for return value.

Usage

wp_handle_upload( $file, $overrides, $time );
$file(array) (required) (passed by reference — &)
Reference to a single element of $_FILES. Call the function once for each uploaded file. See _wp_handle_upload() for accepted values.
$overrides(array|false)
An associative array of names => values to override default variables. See _wp_handle_upload() for accepted values.
Default: false
$time(string)
Time formatted in 'yyyy/mm'.
Default: null

Examples

0

#1 Downloading a file (Example of using the function)

Shows how to upload a file to the WP "uploads" directory, which is passed in the form. Let our form look like this:

<form enctype="multipart/form-data" action="" method="POST">
	<?php wp_nonce_field( 'my_file_upload', 'fileup_nonce' ); ?>
	<input name="my_file_upload" type="file" />
	<input type="submit" value="Upload file" />
</form>

The attribute enctype="multipart/form-data" is required for the form to handle files. Otherwise the field type="file" simply will not pass anything to $_FILES.

Then the code for loading the file will be as follows:

if( wp_verify_nonce( $_POST['fileup_nonce'], 'my_file_upload' ) ){

	if ( ! function_exists( 'wp_handle_upload' ) ) {
		require_once ABSPATH . 'wp-admin/includes/file.php';
	}

	$file = & $_FILES['my_file_upload'];

	$overrides = [ 'test_form' => false ];

	$movefile = wp_handle_upload( $file, $overrides );

	if ( $movefile && empty( $movefile['error'] ) ) {
		echo "The file was successfully uploaded.";
		print_r( $movefile );
	}
	else {
		echo $movefile['error'];
	}
}

Or for multiple file upload.

$files = & $_FILES['my_file_upload'];

foreach ( $files['name'] as $key => $value ) {

	if( empty( $files['name'][ $key ] ) ){
		continue;
	}

	$file = array(
		'name'     => $files['name'][ $key ],
		'type'     => $files['type'][ $key ],
		'tmp_name' => $files['tmp_name'][ $key ],
		'error'    => $files['error'][ $key ],
		'size'     => $files['size'][ $key ],
	);

	$movefile = wp_handle_upload( $file, [ 'test_form' => false ] );

	if( $movefile && empty( $movefile['error'] ) ){
		echo "The file was successfully uploaded.";
		print_r( $movefile );
	}
	else {
		echo $movefile['error'];
	}

}

Notes

Changelog

Since 2.0.0 Introduced.

wp_handle_upload() code WP 6.4.3

function wp_handle_upload( &$file, $overrides = false, $time = null ) {
	/*
	 *  $_POST['action'] must be set and its value must equal $overrides['action']
	 *  or this:
	 */
	$action = 'wp_handle_upload';
	if ( isset( $overrides['action'] ) ) {
		$action = $overrides['action'];
	}

	return _wp_handle_upload( $file, $overrides, $time, $action );
}