MIME type), or null for the site's allowed types. * @return string The stored file's path. * @throws \RuntimeException With private_storage_upload when WordPress refuses the upload or stores it elsewhere. */ public static function receive_upload( array $file, string $dir, string $name, ?array $mimes = null ): string { require_once ABSPATH . 'wp-admin/includes/file.php'; $dir = rtrim( wp_normalize_path( $dir ), '/' ); $file['name'] = $name; // Only for this call: WordPress's uploader writes into this private folder and keeps the name chosen here. $target = static function ( $uploads ) use ( $dir ) { return array_merge( (array) $uploads, array( 'path' => $dir, 'url' => '', 'subdir' => '', 'basedir' => $dir, 'baseurl' => '', 'error' => false, ) ); }; $named = static function () use ( $name ) { return $name; }; add_filter( 'upload_dir', $target, PHP_INT_MAX ); try { $done = wp_handle_upload( $file, array( 'test_form' => false, // The caller checked its own form's nonce. 'mimes' => $mimes, 'unique_filename_callback' => $named, ) ); } finally { remove_filter( 'upload_dir', $target, PHP_INT_MAX ); } $path = is_array( $done ) && empty( $done['error'] ) && is_string( $done['file'] ?? null ) ? wp_normalize_path( $done['file'] ) : ''; if ( $dir . '/' . $name !== $path || is_link( $path ) || ! is_file( $path ) ) { if ( '' !== $path && ! is_link( $path ) && is_file( $path ) ) { wp_delete_file( $path ); } throw new \RuntimeException( 'private_storage_upload' ); } // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_chmod -- Enforce owner-only local permissions on a private staged file. @chmod( $path, 0600 ); return $path; } }