...

View Full Version : Renaming an uploaded file before you move it



bubbles19518
01-07-2007, 11:01 PM
I have this:


$uploadpath = "uploads/"
$filename = $_FILES['externalfile']['name'];
$uploadfile = $uploadpath.$filename;
echo 'uploading your ' . $filename . '... '; flush();
if (move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadfile))
{

echo '<font color=green>Done!</font><br />';

}
else
{

die('<font color=red>Error:</font> could not move file.');

}
flush();

Is a block of code from my upload script. I want when I move the file to change the name to have a random number at the end, rand(1,9999)... To prevent duplicates. I tried this:

$uploadfile = $uploadpath.$filename.rand(1,9999);
But it didnt work, any help?

Majoracle
01-07-2007, 11:29 PM
I don't think you can rename it before actually moving it from the temp location, but you can right after the move:


$uploadpath = "uploads/"
$filename = $_FILES['externalfile']['name'];
$uploadfile = $uploadpath.$filename;

echo 'uploading your ' . $filename . '... '; flush();
if (move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadfile))
{
$uploadnewpath = $uploadpath.$filename.rand(1,9999);
rename($uploadfile, $uploadnewpath) or die();
echo '<font color=green>Done!</font><br />';
}
else
{
die('<font color=red>Error:</font> could not move file.');
}
flush();

bubbles19518
01-09-2007, 03:01 AM
I changed it to this:


$uploadfile = $uploadpath.$filename;
$uploadnewpath = $uploadpath.$filename.rand(1,9999);
rename($uploadfile, $uploadnewpath);
if (move_uploaded_file($_FILES['externalfile']['tmp_name'], $uploadnewpath))
{

echo '<font color=green>Done!</font><br />';

}

Since I cant rename it after I move it if there is already a file with that name in the folder. So Im trying to rename it before I move it, but its not working and I dont know why.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum