Welcome Guest, Not a member yet? Register   Sign In
Checking directory listing for unique filename
#1

[eluser]skunkbad[/eluser]
I've got some code here, which is checking a directory listing to see if there is a unique filename before upload. It's different than the Upload library's check, because it can be used with the FTP class or cURL. I'll be replacing a function in Community Auth with this one tomorrow morning, and thought it may be useful to some of you. If you see or experience any problems, let me know.

Expected output is a unique filename. For instance, if uploaded file is named a.pdf, and there is already an a.pdf, the returned filename is a(2).pdf. If a(2).pdf also exists, the returned filename is a(3).pdf, and so on.

Code:
/**
* Different than the CI Upload class' set_filename function,
* this function takes a supplied directory listing and checks
* that the supplied filename is not in it. If it is, it adds a
* number, in parenthesis, to the end of the filename.
*/
function _force_unique_filename( $dir_list, $file_name, $x = 1 )
{
/**
  * Dir list may be an array of file names, or in the case of
  * cURL, the list may be supplied as a string. If an array, we
  * just convert the array to a string so it is checked as a string.
  */
if( is_array( $dir_list ) )
{
  $dir_list = implode( ' ', $dir_list );
}

while( strpos( $dir_list, $file_name ) !== FALSE )
{
  // Increment the number we are using in a filename suffix "($x)"
  $x++;

  // Use pathinfo to break apart the filename
  $info = pathinfo( $file_name );

  // Get the file extension of the file
  $ext = '.' . $info['extension'];

  // Get the name of the file without extension
  $file_name = basename( $file_name, $ext );

  // Remove the filename suffix before adding a new one
  $pattern = '/\(\d+\)/';
  $replacement = '';
  $file_name = preg_replace( $pattern, $replacement, $file_name );
  
  // Add new filename suffix
  $file_name .= '(' . (string) $x . ')' . $ext;
}

return $file_name;
}




Theme © iAndrew 2016 - Forum software by © MyBB