Page 1 of 1

renaming uploaded files when file exists

Posted: Thu Feb 08, 2007 3:21 am
by ryuuka
hello again

i am nearly done with this neat site of mine
but now i want it to automaticly rename the uploaded files if said file already exists
what i also want to do is that this name is at the same time get this new file name in the database

piece of code:

Code: Select all

$Datum_upload = date('j-n-Y g:i:s'); 
$upload_mail = $_POST['upload_mail'];
$download_mail = $_POST['download_mail'];
$Naam = $_POST['Naam_werknemer'];
$beschrijving = $_POST['beschrijving'];
$Filenaam = $_FILES["userfile"]["name"];
$Formaat_bytes = $_FILES['userfile']['size'];
$Formaat = round($Formaat_bytes / 1048576, 2);
$type = $_FILES['userfile']['type'];


//if the $_files variable isn't empty the files are moved
 if(!empty($_FILES["userfile"])) 
{ 
	// this is the upload dir
	$uploaddir = "D:/upload/";
	// hier worden de bestanden naar een gegeven locatie verplaatst 
	if (move_uploaded_file($_FILES["userfile"]["tmp_name"], $uploaddir . $_FILES["userfile"]["name"])) 
	{
	$rs = $objConn->Execute("INSERT INTO Gispen_file_distro (bestandsnaam, naam_gebruiker, email_verzender, email_ontvanger, beschrijving, Grootte_bestand, datum_upload, download)
	VALUES('$Filenaam','$Naam','$upload_mail','$download_mail', '$beschrijving','$Formaat','$Datum_upload','onbevestigd')");
any idea's or functions that will help me do this?

Posted: Thu Feb 08, 2007 4:05 am
by Chris Corbyn

Code: Select all

$filename = get_unique_filename($_FILES["field"]["name"], "/path/to/directory");

function get_unique_filename($name, $path)
{
    $full_path = $path . "/" . $name;
    if (file_exists($full_path))
    {
        $i = 0;
        $new_name = null;
        do
        {
            ++$i;
            $new_name = preg_replace("/^(.*?)(?:\\.([^\\.]*))?\$/", "\$1_$i.\$2", $name);
            $full_path = $path . "/" . $new_name;
        } while (file_exists($full_path));
        $name = $new_name;
    }
    
    return $name;
}

Posted: Thu Feb 08, 2007 4:54 am
by louie35
I prefer no to need to rename files if they exit.
Instead on uploading i just add 3 number to the file at random so i don't run into problems.

Code: Select all

$new_name  = strtolower(mt_rand (1, 999)."_".$new_name );

Posted: Thu Feb 08, 2007 6:41 am
by ryuuka
thanks for the response

d11 your file name confuses me a little though:

what is the "/path/to/directory" line for?

is that the dir where the files need to be checked or the one where

Code: Select all

move_uploaded_file
is reffering to?