WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp handle upload

Description

Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type, and moving the file to the appropriate directory within the uploads directory.

Usage

<?php wp_handle_upload$file$overrides$time ); ?>

Parameters

$file
(array) (required) Reference to a single element of $_FILES. Call the function once for each uploaded file. Passed by reference, so you must pass a variable, not a literal.
Default: None
$overrides
(array) (optional) An associative array to override default behaviors. When called while handling a form, 'action' must be set to match the 'action' parameter in the form or the upload will be rejected. When there is no form being handled, use 'test_form' => false to bypass this test, and set 'action' to something other than the default ("wp_handle_upload") to bypass security checks requiring the file in question to be a user-uploaded file.
Default: false
$time
(string) (optional) Time formatted in 'yyyy/mm'. Passed to wp_upload_dir().
Default: NULL

Examples

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

$uploadedfile = $_FILES['file'];

$upload_overrides = array( 'test_form' => false );

$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );

if ( $movefile && ! isset( $movefile['error'] ) ) {
    echo "File is valid, and was successfully uploaded.\n";
    var_dump( $movefile );
} else {
    /**
     * Error generated by _wp_handle_upload()
     * @see _wp_handle_upload() in wp-admin/includes/file.php
     */
    echo $movefile['error'];
}

Return values

On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).

The return values on success:

file 
(string) The local path to the uploaded file.
url 
(string) The public URL for the uploaded file.
type 
(string) The MIME type.

type and file may be used with wp insert attachment().

Further Reading

Source File

wp_handle_upload() is located in wp-admin/includes/file.php.

Related

Upload Functions: media_handle_upload(), media_handle_sideload(), wp_handle_upload(), wp_import_handle_upload(), wp_handle_sideload(), media_sideload_image()

See also index of Function Reference and index of Template Tags.