wp_delete_file_from_directory()WP 4.9.7

Deletes the specified file from the specified folder, only if the file is located in that folder.

What the function does:

  1. Converts the specified paths (to the file and folder) from relative to absolute realpath().
  2. Checks using the obtained paths whether the specified file is in the specified folder.
  3. Calls wp_delete_file( $file )

You can specify a file that is located in a nested folder, the check will pass. For example:

$file      = 'www/wp-content/uploads/2019/03/image.jpg';
$directory = 'www/wp-content/uploads/';

No Hooks.

Returns

true|false. True on success, false on failure.

Usage

wp_delete_file_from_directory( $file, $directory );
$file(string) (required)
Absolute path to the file to be deleted.
$directory(string) (required)
Absolute path to the directory (folder).

Examples

0

#1 Delete the file test.html from the uploads directory

$upldir_info = wp_get_upload_dir();
$uploads_dir = $upldir_info['basedir']; // uploads path

wp_delete_file_from_directory( "$uploads_dir/test.html", $uploads_dir ); // true or false

Changelog

Since 4.9.7 Introduced.

wp_delete_file_from_directory() code WP 6.9.1

function wp_delete_file_from_directory( $file, $directory ) {
	if ( wp_is_stream( $file ) ) {
		$real_file      = $file;
		$real_directory = $directory;
	} else {
		$real_file      = realpath( wp_normalize_path( $file ) );
		$real_directory = realpath( wp_normalize_path( $directory ) );
	}

	if ( false !== $real_file ) {
		$real_file = wp_normalize_path( $real_file );
	}

	if ( false !== $real_directory ) {
		$real_directory = wp_normalize_path( $real_directory );
	}

	if ( false === $real_file || false === $real_directory || ! str_starts_with( $real_file, trailingslashit( $real_directory ) ) ) {
		return false;
	}

	return wp_delete_file( $file );
}