Вот функция, которую я использую:
function cleanup_name($name){ //accepts name and cleans it up.
$finalDir='/home/username/uploads';
# Go to all lower case for consistency
$name = strtolower($name);
//echo("Name is $name<br>");
$matches=split('\.',$name);
foreach ($matches as $key=>$value){
$exkey=$key;
$exvalue=$value; //if there is more than one period, this will find the actual extension.
//echo("Key $key|$exkey Value $value|$exvalue<br>");
}
if ($exkey<1){die('The file must have an extension.');}
$extension=".".$exvalue;
$loop=0;
while ($loop<($exkey)){
if ($loop<($exkey-1)){$matches[$loop]=".".$matches[$loop];} // this puts extra periods back into the string, but the borrowed code will replace them with underscores.
$stem.=$matches[$loop];
$loop++;
}
//echo("Stem is $stem<br>");
//echo("Extension is $extension<br>");
# Convert whitespace of any kind to single underscores
$stem = preg_replace('/\s+/', '_', $stem);
# Remove any remaining characters other than A-Z, a-z, 0-9 and _
$stem = preg_replace('/[^\w]/', '', $stem);
# Make sure the file extension has no odd characters
if (($extension != '') &&
(!preg_match('/^\.\w+$/', $extension)))
{
echo("odd characters in extension");
//die("Bad file extension");
return FALSE;
}
$safeExtensions = array(
'.zip',
'.psd',
'.pdf',
'.jpg',
'.jpeg',
'.gif',
'.rar',
'.gz',
'.ai',
'.eps',
'.bmp',
'.pub',
'.xls',
'.doc',
'.wpd',
'.rtf',
'.tiff',
'.tif',
'.pcx',
'.ttf',
'.png',
'.txt',
'.mp3',
'.avi',
'.mov',
'.wav'
);
if (!in_array($extension, $safeExtensions)) {
echo("Extension "$extension" not approved.");
//die("File extension not approved");
return FALSE;
}
# Search for a unique filename by adding a number to the
# stem (first we try without, of course)
$suffix = '';
while (file_exists($finalDir."/".$stem.$suffix.$extension)) {
if ($suffix == '') {
$suffix = '0';
} else {
$suffix++;
}
}
# Put the full name back together
$name = "$stem$suffix$extension";
return $name;
}
Обратите особое внимание на раздел с этим: "while (file_exists ..."