How to rename file on upload rather than overwrite it?

I have this script which uploads a file to a desired location on the server - but it overwrites any same-named existing files.

What do I need to add to it to automatically rename rather than lose files by overwriting?

I guess I need to alter this line below, but have no idea how?

[php] if(move_uploaded_file($_FILES[‘uploaded’][‘tmp_name’], $target)) [/php]

The chances are that most of the files uploaded by users will be called “cv.doc” or similar and I don’t want to lose any.

Here’s my HTML code:

[php]
Upload Your CV:

[/php]

And the crucial PHP part:

[php] <?php
$target = “upload/”;
$target = $target . basename( $_FILES[‘uploaded’][‘name’]) ;
$ok=1;

//This is our size condition
if ($uploaded_size > 350000)
{
echo “Your file is too large.
”;
$ok=0;
}

//This is our limit file type condition
if ($uploaded_type ==“text/php”)
{
echo “No PHP files
”;
$ok=0;
}

//Here we check that $ok was not set to 0 by an error
if ($ok==0)
{
Echo “Sorry your file was not uploaded”;
}

//If everything is ok we try to upload it
else
{
if(move_uploaded_file($_FILES[‘uploaded’][‘tmp_name’], $target))
{
echo "Thank you! Your file “. basename( $_FILES[‘uploadedfile’][‘name’]). " has been uploaded. We will contact you shortly.”;
}
else
{
echo “Sorry, there was a problem uploading your file.”;
}
}
?> [/php]

Ok I’ve solved my own problem - here’s the answer:

Replace this:

[php]$target = “upload/”;
$target = $target . basename( $_FILES[‘uploaded’][‘name’]) ;
$ok=1;[/php]

With this:

[php]$name=time();
$target = “upload/”;
$target = $target .$name. basename( $_FILES[‘uploaded’][‘name’]);
$ok=1; [/php]

This adds a time stamp to the start of the file thus allowing files of the same name to be uploaded without overwriting.

Sponsor our Newsletter | Privacy Policy | Terms of Service