wp_unique_filename() – Gets a filename that is sanitized and unique for the given directory.

You appear to be a bot. Output may be restricted

Description

Gets a filename that is sanitized and unique for the given directory.

If the filename is not unique, then a number will be added to the filename before the extension, and will continue adding numbers until the filename is unique. The callback function allows the caller to use their own method to create unique file names. If defined, the callback should take three arguments:

  • directory, base filename, and extension – and return a unique filename.

Usage

$string = wp_unique_filename( $dir, $filename, $unique_filename_callback );

Parameters

$dir
( string ) required – Directory.
$filename
( string ) required – File name.
$unique_filename_callback
( callable ) optional – Callback. Default null.

Returns

string New filename, if given wasn't unique.

Source

File name: wordpress/wp-includes/functions.php
Lines:

1 to 100 of 247
function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  // Sanitize the file name before we begin processing.
  $filename = sanitize_file_name( $filename );
  $ext2     = null;

  // Initialize vars used in the wp_unique_filename filter.
  $number        = '';
  $alt_filenames = array();

  // Separate the filename into a name and extension.
  $ext  = pathinfo( $filename, PATHINFO_EXTENSION );
  $name = pathinfo( $filename, PATHINFO_BASENAME );

  if ( $ext ) {
    $ext = '.' . $ext;
  }

  // Edge case: if file is named '.ext', treat as an empty name.
  if ( $name === $ext ) {
    $name = '';
  }

  /*
	 * Increment the file number until we have a unique file to save in $dir.
	 * Use callback if supplied.
	 */
  if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
    $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  } else {
    $fname = pathinfo( $filename, PATHINFO_FILENAME );

    // Always append a number to file names that can potentially match image sub-size file names.
    if ( $fname && preg_match( '/-(?:\d+x\d+|scaled|rotated)$/', $fname ) ) {
      $number = 1;

      // At this point the file name may not be unique. This is tested below and the $number is incremented.
      $filename = str_replace( "{$fname}{$ext}", "{$fname}-{$number}{$ext}", $filename );
    }

    /*
		 * Get the mime type. Uploaded files were already checked with wp_check_filetype_and_ext()
		 * in _wp_handle_upload(). Using wp_check_filetype() would be sufficient here.
		 */
    $file_type = wp_check_filetype( $filename );
    $mime_type = $file_type['type'];

    $is_image    = ( ! empty( $mime_type ) && str_starts_with( $mime_type, 'image/' ) );
    $upload_dir  = wp_get_upload_dir();
    $lc_filename = null;

    $lc_ext = strtolower( $ext );
    $_dir   = trailingslashit( $dir );

    /*
		 * If the extension is uppercase add an alternate file name with lowercase extension.
		 * Both need to be tested for uniqueness as the extension will be changed to lowercase
		 * for better compatibility with different filesystems. Fixes an inconsistency in WP < 2.9
		 * where uppercase extensions were allowed but image sub-sizes were created with
		 * lowercase extensions.
		 */
    if ( $ext && $lc_ext !== $ext ) {
      $lc_filename = preg_replace( '|' . preg_quote( $ext ) . '$|', $lc_ext, $filename );
    }

    /*
		 * Increment the number added to the file name if there are any files in $dir
		 * whose names match one of the possible name variations.
		 */
    while ( file_exists( $_dir . $filename ) || ( $lc_filename && file_exists( $_dir . $lc_filename ) ) ) {
      $new_number = (int) $number + 1;

      if ( $lc_filename ) {
        $lc_filename = str_replace(
          array( "-{$number}{$lc_ext}", "{$number}{$lc_ext}" ),
          "-{$new_number}{$lc_ext}",
          $lc_filename
        );
      }

      if ( '' === "{$number}{$ext}" ) {
        $filename = "{$filename}-{$new_number}";
      } else {
        $filename = str_replace(
          array( "-{$number}{$ext}", "{$number}{$ext}" ),
          "-{$new_number}{$ext}",
          $filename
        );
      }

      $number = $new_number;
    }

    // Change the extension to lowercase if needed.
    if ( $lc_filename ) {
      $filename = $lc_filename;
    }

    /*
		 * Prevent collisions with existing file names that contain dimension-like strings
		 * (whether they are subsizes or originals uploaded prior to #42437).
 

 View on GitHub View on Trac