Skip to content

Instantly share code, notes, and snippets.

@weaverryan
Created December 4, 2010 16:04
Show Gist options
  • Save weaverryan/728282 to your computer and use it in GitHub Desktop.
Save weaverryan/728282 to your computer and use it in GitHub Desktop.
Offers a way to save files as a cleaned, unique version of the original filename in symfony1
<?php
/**
* Offers a way to save files as a cleaned, unique version of the original filename.
*
* Use this as the 'validated_file_class' option on sfValidatorFile.
*
* Bad characters are replaced by the replaceCharacter string. Unique filenames
* are created by appending an increasing -# to the end of the basename
* of the uploaded file.
*
* @author Ryan Weaver <ryan@thatsquality.com>
*/
class wfValidatedFileNamer extends sfValidatedFile
{
/**
* The "safe" character to replace bad characters within a filename
*
* @var string
*/
public static $replaceCharacter = '-';
/**
* @see sfValidatedFile
*/
public function generateFilename()
{
$cleanedName = $this->cleanFilename($this->getOriginalName());
// if no file by the cleaned original name already exists, just return the originally uploaded filename
if (!file_exists($this->getPath().'/'.$cleanedName))
{
return $cleanedName;
}
// iterate until we find a unique filename of format original_filename-n.ext where n is an integer
$i = 1;
while (1)
{
$basename = str_replace($this->getOriginalExtension(), '', $cleanedName);
$newFilename = sprintf('%s-%s%s', $basename, $i, $this->getOriginalExtension());
if (!file_exists($this->getPath().'/'.$newFilename))
{
return $newFilename;
}
$i++;
}
}
/**
* Removes non-filename safe characters and replaces them with a replace character
*
* Source http://iamcam.wordpress.com/2007/03/20/clean-file-names-using-php-preg_replace/
*
* @param string $raw The raw filename
* @return string A cleaned filename
*/
protected function cleanFilename($raw)
{
// find and then remove all of the bad character
$pattern="/([[:alnum:]_\.-]*)/";
$cleaned = str_replace(str_split(preg_replace($pattern, self::$replaceCharacter, $raw)), self::$replaceCharacter, $raw);
// remove duplicate $replace characters
$pattern = '#('.preg_quote(self::$replaceCharacter).'){2,}#';
return preg_replace($pattern, self::$replaceCharacter, $cleaned);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment