wp_upload_bits()
概述
wp_upload_bits() 函数用于在 WordPress 上传目录中创建文件,基于给定的内容而非移动已上传文件。它处理文件权限、错误检查,并返回包含文件路径、URL 等信息的数组。
关键要点
- 函数用途:在 upload 文件夹中创建新文件,内容来自 $bits 参数,不处理文件上传移动。
- 参数说明:$name(文件名,必需)、$deprecated(已弃用,设为 null)、$bits(文件内容,必需)、$time(时间格式,可选)。
- 返回值:数组包含 'file'(文件路径)、'url'(文件 URL)、'type'(文件类型)、'error'(错误信息或 false)。
- 错误处理:如果出错,返回数组的 'error' 键包含错误消息;成功时 'error' 为 false。
- 权限设置:自动设置新文件的权限。
- 相关 Hook:使用 apply_filters('wp_upload_bits', ...) 和 apply_filters('wp_handle_upload', ...) 进行过滤。
代码示例
$upload = wp_upload_bits($_FILES["field1"]["name"], null, file_get_contents($_FILES["field1"]["tmp_name"]));注意事项
- 函数不移动上传文件,需先读取内容再调用。
- 确保文件名非空,否则返回错误。
- 文件类型检查通过 wp_check_filetype() 进行,用户需有 'unfiltered_upload' 权限上传无扩展名文件。
- 在多站点环境中,会清理目录大小缓存。
Creates a file in the upload folder with given content.
Description
If there is an error, then the key ‘error’ will exist with the error message.
If success, then the key ‘file’ will have the unique file path, the ‘url’ key will have the link to the new file. and the ‘error’ key will be set to false.
This function will not move an uploaded file to the upload folder. It will create a new file with the content in $bits parameter. If you move the upload file, read the content of the uploaded file, and then you can give the filename and content to this function, which will add it to the upload folder.
The permissions will be set on the new file automatically by this function.
Parameters
$namestringrequired-
Filename.
$deprecatednull|stringrequired-
Never used. Set to null.
$bitsstringrequired-
File content
$timestring|nulloptional-
Time formatted in
'yyyy/mm'.Default:
null
Source
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'
);
}
Hooks
- apply_filters( ‘wp_handle_upload’, array $upload, string $context )
-
Filters the data array for the uploaded file.
- apply_filters( ‘wp_upload_bits’, array|string $upload_bits_error )
-
Filters whether to treat the upload bits as an error.
Changelog
| Version | Description |
|---|---|
| 2.0.0 | Introduced. |
Skip to note 5 content
shossain571
The function returns an array with the following keys:
Skip to note 6 content
kacprusz
If you have multiple files upload, you must get length of arrays in your $_FILES array, after that loop with for.
if(isset($_FILES['your_field'])){ $length = sizeof($_FILES['your_field']['name']); for ($i=0; $i < $length; $i++) { wp_upload_bits($_FILES['your_field']['name'][$i], null, file_get_contents($_FILES['your_field']['tmp_name'][$i])); } }Skip to note 7 content
Codex
Basic Example
A simple example assuming the request was made from a form with a file field called field1:
$upload = wp_upload_bits($_FILES["field1"]["name"], null, file_get_contents($_FILES["field1"]["tmp_name"]));The function attempts to save a copy of the uploaded file to the upload directory set in the WordPress settings. It also performs security checks (file type, size, etc) and returns errors if any (see Return Values above). You might want to remove the tmp file after uploading.
Skip to note 8 content
Wilhelm Burger
HOW TO UPLOAD FILES 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/'; $wp_filesystem->mkdir( $content_directory . 'CustomDirectory' ); $target_dir_location = $content_directory . 'CustomDirectory/'; if ( isset( $_POST['submittheform'] ) && isset( $_FILES['fileToUpload'] ) ) { $name_file = $_FILES['fileToUpload']['name']; $tmp_name = $_FILES['fileToUpload']['tmp_name']; if ( move_uploaded_file( $tmp_name, $target_dir_location . $name_file ) ) { echo "File was successfully uploaded"; } else { echo "The file was not uploaded"; } }