WP-Mix

A fresh mix of code snippets and tutorials

WordPress Create Upload Files and Directories

This tutorial explains how to create new files and directories in the WordPress /uploads/ folder.

Create new file in the uploads directory

WordPress provides the function wp_upload_bits() to create a new file in the /uploads/ directory. Here is a quick example showing possible usage:

$filename = sanitize_text_field($_FILES["image"]["name"]);
$deprecated = null;
$bits = file_get_contents($_FILES["image"]["tmp_name"]);
$time = current_time('mysql');

$upload = wp_upload_bits($filename, $deprecated, $bits, $time);

In this example, we assume a file input named image. Upon form submission, this code attempts to save a copy of the image to the WordPress /uploads/ directory.

The function wp_upload_bits() performs basic security checks for the uploaded file and includes any errors in the return array, $upload. The $upload array also includes the file system path and the URL of the uploaded file.

Note that PHP automatically deletes the temp file so there is no need for special treatment in that regard. Refer to the Codex for more details (see footer references).

Create new subdirectory in the uploads directory

To create directories in WordPress, we can use the WP function wp_mkdir_p(). This function may be used to create directories just about anywhere, but when using to create subdirectories in the /uploads/ directory, it’s helpful also to use wp_upload_dir() to get the necessary path information.

To give you a better idea, here is a simple example provided by the WP Codex:

global $current_user;
get_currentuserinfo();
$upload_dir = wp_upload_dir(); 
$user_dirname = $upload_dir['basedir'] . '/' . $current_user->user_login;
if(!file_exists($user_dirname)) wp_mkdir_p($user_dirname);

This code gets the required information about the uploads directory and uses it to create a subdirectory via wp_mkdir_p(). Alternately we can use the PHP function mkdir, as demonstrated in the following example:

$upload = wp_upload_dir();
$upload_dir = $upload['basedir'] . $directory_path;
$permissions = 0755;
$oldmask = umask(0);
if (!is_dir($upload_dir)) mkdir($upload_dir, $permissions);
$umask = umask($oldmask);
$chmod = chmod($upload_dir, $permissions);

Here we also are using wp_upload_dir() to retrieve the required information about the /uploads/ directory. FWIW, I use a variation of this technique in my plugin, USP Pro (User Submitted Posts Pro).

Note

The techniques here probably are best for quick implementations and smaller projects. For more extensive/advanced file implementations, check out WP’s Filesystem API. Thanks to @eliorivero for the heads up!

References

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress