Page 1 of 1

Renaming file on upload..?

Posted: Fri Dec 06, 2002 5:17 am
by Darkside
Using this script am I able to change the name of the file apon upload.

Code: Select all

<?php

if(!(copy($_FILES&#1111;'userfile']&#1111;'tmp_name'], "Upload/" . $_FILES&#1111;filename']&#1111;'name']))) die("Cannot upload files.");
echo "Upload Complete!";

?>
My aim is so that users can upload jpeg of any file name and they will get renamed to 'fubar001, fubar-002'

Please help

Thanks

Posted: Fri Dec 06, 2002 5:46 am
by volka
then just $_FILES['filename']['name'] by the name you would like to use ;)
to find the next number to append to the filename you might use something like

Code: Select all

<?php
function getNextSerial($prefix, $path)
{
	$max = -1;
	$dir = opendir($path);
	while($fname = readdir($dir))
	{
		if(strpos($fname, $prefix) === (int)0)
			$max = max($max, (int)substr($fname, strlen($prefix)));
	}
	return ++$max;
}

$postfix = strrchr($_FILES['filename']['name'], '.');
$fname = 'Upload/fubar' . getNextSerial('fubar', 'Upload').$postfix;
echo $fname;
?>
if you want to keep the number-width (001) take a look at http://www.php.net/manual/en/function.sprintf.php

the determination of the filetype is a bit trickier.
almost any unix system offers the program file that determines the filetype by looking at the first few characters in the file. So if your script is running on an unix-style system you might use exec(), system(), ... to let file(1) check the filetype.
But e.g. windows systems lack this command and php itself has it (according to the manual http://www.php.net/manual/en/function.m ... t-type.php ) only in the CVS version.
testing the postfix is a simple approach which is far from bulletproof but -hmm- easy ;)