使用给定内容在上传文件夹中创建文件。

原型

wp_upload_bits( string $name, null|string $deprecated, mixed $bits, string $time = null )

描述

如果出现错误,则错误消息中将存在密钥“错误”。如果成功,那么键’file’将具有唯一的文件路径,‘url’键将具有指向新文件的链接。并且’error’键将设置为false。

参数

$name (string) (Required) 文件名。

$deprecated (null|string) (Required) 没用过。设为null。

$bits (mixed) (Required) 文件内容

$time (string) (Optional)  时间格式为’yyyy / mm’。

返回值

(array)  

源文件

路径:wp-includes/functions.php

<?php
...
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, this file type is not permitted for security reasons.' ) );
	$upload = wp_upload_dir( $time );
	if ( $upload['error'] !== false )
		return $upload;
	/**
	 * Filters whether to treat the upload bits as an error.
	 *
	 * Passing a non-array to the filter will effectively short-circuit preparing
	 * the upload bits, returning that value instead.
	 *
	 * @since 3.0.0
	 *
	 * @param mixed $upload_bits_error An array of upload bits data, or a non-array error 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 ( 0 === strpos( $upload['basedir'], ABSPATH ) )
			$error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
		else
			$error_path = 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( '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";
	/** 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' );
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_upload_bits/