wp_upload_bits()WP 2.0.0

Creates a file with the specified content in the uploads folder (upload). Returns the uploaded file data. Does not store file data in the DB.

If the upload triggers an error, the "error" key of the returned array will contain the error message.

The function compares the file extension against the list of allowed upload extensions — see wp_check_filetype(), the maximum allowed size, etc. Important — when checking the extension the real MIME type of the file is not checked; if you need to verify the real MIME type, use the wp_check_filetype_and_ext().

Makes the file name unique.

This function does not move an already uploaded file into the uploads folder. It creates a new file with the content passed in the $bits parameter. If you need to move a file, read the file contents and then pass the data to this function; it will create a new file. After that the old file can be deleted.

File permissions will be set automatically according to system settings.

Hooks from the function

Returns

Array. Array of data about the function's operation, which contains the following data:

If the file is uploaded successfully the "file" key will contain the full path to the file on the server, and the "url" key will contain the file URL.

array(
	'file'  => '/var/www/wp-content/uploads/2010/03/example.pdf', // path
	'url'   => 'http://example.com/wp-content/uploads/2010/03/example.pdf', // url
	'type'  => 'application/pdf',
	'error' => false, // error message is placed here on failure
)

Usage

$upload = wp_upload_bits( $name, $deprecated, $bits, $time );
$name(string) (required)
The name of the file to create. You must include the full name with extension.
$deprecated(null) (required)
Not used, should be set to null.
$bits(string) (required)
The content of the file to create as a string. It is usually obtained using file_get_contents().
$time(string)
Time in the format YYYY/MM — where to place the file in the uploads folder. If the checkbox "Organize my uploads into month- and year-based folders" is unchecked in settings, this parameter has no meaning. By default, the file will be uploaded into the current month and year.
Default: null

Examples

1

#1 How to upload file to a custom directory in WordPress

This example uploads a PDF document in the wp-content/uploads/customDirectory folder:

<form action="" method="post" enctype="multipart/form-data">
  Select image to upload:
  <input type="file" name="fileToUpload" id="fileToUpload">
  <br>
  <input type="submit" value="Upload Image" name="submittheform">
</form>
global $wp_filesystem;
WP_Filesystem();

$content_directory = $wp_filesystem->wp_content_dir() . 'uploads';
$custom_dirname = 'CustomDirectory';
$wp_filesystem->mkdir( "$content_directory/$custom_dirname" );
$target_dir_location = "$content_directory/$custom_dirname";

if ( isset( $_POST['submittheform'] ) && isset( $_FILES['fileToUpload'] ) ) {

	$name_file = $_FILES['fileToUpload']['name'];
	$tmp_name = $_FILES['fileToUpload']['tmp_name'];

	$cont = file_get_contents( $tmp_name );
	$upload = wp_upload_bits( $name_file, null, $cont );

	// let's check error
	if( $upload['error'] ){
		echo 'The post caused an error: '. $upload['error'];
	}
	else {
		$move = move_uploaded_file( $upload['file'], "$target_dir_location/$name_file" );

		if ( $move ) {
			echo "File was successfully uploaded";
		}
		else {
			echo "The file was not uploaded";
		}
	}

}
0

#2 Demo

This example shows how to create a file in the download folder. Let's create an image. Let's take the content of an external picture with file_get_contents() and put it in the download folder of our site:

$cont = file_get_contents('http://example.com/some_img.png');
$new_file_name = 'uploaded.png';
$upload = wp_upload_bits( $new_file_name, null, $cont );

// let's check if the post
if( $upload['error'] )
	echo 'The post caused an error: '. $upload['error'];
else
	echo 'The post is successful! File path: '. $upload['file'] .'; File URL: '. $upload['url'];

In the example we see that the $upload array looks like this:

Array ( 
	[file] => /home/user/site/public_html/wp-content/2013/03/uploaded.png 
	[url] => http://example.com/wp-content/uploads/2013/03/uploaded.png 
	[type] => image/png
	[error] => 
)

Now, for example, we can display the downloaded picture using the url:

<img src="<?php echo $upload['url'] ?>" />
0

#3 Creating a file from a form

This example shows how to create a file passed in a form. It is assumed that the request is made from a form with field1:

$upload = wp_upload_bits( 
	$_FILES["field1"]["name"],  
	null, 
	file_get_contents( $_FILES["field1"]["tmp_name"] ) 
);

This function tries to save a copy of the uploaded file to the WordPress upload directory. It also performs a security function by checking the file (file type, size, etc.) and returns an error if any of the parameters are not allowed. After uploading, it is advisable to delete the temporary file.

Changelog

Since 2.0.0 Introduced.

wp_upload_bits() code WP 7.0

function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
	if ( ! empty( $deprecated ) ) {
		_deprecated_argument( __FUNCTION__, '2.0.0' );
	}

	if ( empty( $name ) ) {
		return array( 'error' => __( 'Empty filename' ) );
	}

	$wp_filetype = wp_check_filetype( $name );
	if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) ) {
		return array( 'error' => __( 'Sorry, you are not allowed to upload this file type.' ) );
	}

	$upload = wp_upload_dir( $time );

	if ( false !== $upload['error'] ) {
		return $upload;
	}

	/**
	 * Filters whether to treat the upload bits as an error.
	 *
	 * Returning a non-array from the filter will effectively short-circuit preparing the upload bits
	 * and return that value instead. An error message should be returned as a string.
	 *
	 * @since 3.0.0
	 *
	 * @param array|string $upload_bits_error An array of upload bits data, or error message to return.
	 */
	$upload_bits_error = apply_filters(
		'wp_upload_bits',
		array(
			'name' => $name,
			'bits' => $bits,
			'time' => $time,
		)
	);
	if ( ! is_array( $upload_bits_error ) ) {
		$upload['error'] = $upload_bits_error;
		return $upload;
	}

	$filename = wp_unique_filename( $upload['path'], $name );

	$new_file = $upload['path'] . "/$filename";
	if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
		if ( str_starts_with( $upload['basedir'], ABSPATH ) ) {
			$error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
		} else {
			$error_path = wp_basename( $upload['basedir'] ) . $upload['subdir'];
		}

		$message = sprintf(
			/* translators: %s: Directory path. */
			__( 'Unable to create directory %s. Is its parent directory writable by the server?' ),
			$error_path
		);
		return array( 'error' => $message );
	}

	$ifp = @fopen( $new_file, 'wb' );
	if ( ! $ifp ) {
		return array(
			/* translators: %s: File name. */
			'error' => sprintf( __( 'Could not write file %s' ), $new_file ),
		);
	}

	fwrite( $ifp, $bits );
	fclose( $ifp );
	clearstatcache();

	// Set correct file permissions.
	$stat  = @ stat( dirname( $new_file ) );
	$perms = $stat['mode'] & 0007777;
	$perms = $perms & 0000666;
	chmod( $new_file, $perms );
	clearstatcache();

	// Compute the URL.
	$url = $upload['url'] . "/$filename";

	if ( is_multisite() ) {
		clean_dirsize_cache( $new_file );
	}

	/** This filter is documented in wp-admin/includes/file.php */
	return apply_filters(
		'wp_handle_upload',
		array(
			'file'  => $new_file,
			'url'   => $url,
			'type'  => $wp_filetype['type'],
			'error' => false,
		),
		'sideload'
	);
}