wp_tempnam

Returns a filename of a Temporary unique file.

Description

(string) wp_tempnam( (string) $filename = '', (string) $dir = '' ); 

Please note that the calling function must unlink() this itself.

The filename is based off the passed parameter or defaults to the current unix timestamp, while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.

Returns (string)

a writable filename

Parameters (2)

0. $filename — Optional. (string) => ''
Filename to base the Unique file off. Default empty.
1. $dir — Optional. (string) => ''
Directory to store the file in. Default empty.

Usage

  1. if ( !function_exists( 'wp_tempnam' ) ) { 
  2. require_once ABSPATH . '/wp-admin/includes/file.php'; 
  3.  
  4. // Optional. Filename to base the Unique file off. Default empty. 
  5. $filename = ''; 
  6.  
  7. // Optional. Directory to store the file in. Default empty. 
  8. $dir = ''; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = wp_tempnam($filename, $dir); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-admin/includes/file.php  
  1. function wp_tempnam( $filename = '', $dir = '' ) { 
  2. if ( empty( $dir ) ) { 
  3. $dir = get_temp_dir(); 
  4.  
  5. if ( empty( $filename ) || '.' == $filename || '/' == $filename || '\\' == $filename ) { 
  6. $filename = time(); 
  7.  
  8. // Use the basename of the given file without the extension as the name for the temporary directory 
  9. $temp_filename = basename( $filename ); 
  10. $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename ); 
  11.  
  12. // If the folder is falsey, use its parent directory name instead. 
  13. if ( ! $temp_filename ) { 
  14. return wp_tempnam( dirname( $filename ), $dir ); 
  15.  
  16. // Suffix some random data to avoid filename conflicts 
  17. $temp_filename .= '-' . wp_generate_password( 6, false ); 
  18. $temp_filename .= '.tmp'; 
  19. $temp_filename = $dir . wp_unique_filename( $dir, $temp_filename ); 
  20.  
  21. $fp = @fopen( $temp_filename, 'x' ); 
  22. if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) { 
  23. return wp_tempnam( $filename, $dir ); 
  24. if ( $fp ) { 
  25. fclose( $fp ); 
  26.  
  27. return $temp_filename;