Forum Moderators: coopster

Message Too Old, No Replies

Help with a PHP file upload script

I need help on renaming a file that is uploading if it already exists.

         

Flurpal

10:30 pm on Jul 28, 2009 (gmt 0)

10+ Year Member



Hi! I found a great PHP upload script online, and then I changed it a lot. It works fine for what it was made for...however I want to mod it and add some more function to it. Anyway, here it is (so far).

The upload form:


<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="100000000000000000000000000000000000000000000000" />
Choose a file to upload: <input name="uploaded_file" type="file" /><input type="submit" value="Upload" />
</form>

The script (upload.php):


<?php
//Check that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/file/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done! The file has been saved as: ".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists.";
}
} else {
echo "Error: No file uploaded";
}
?>

As you can see, php stores the file, then sees if it qualifies for being stored. If it does, then it's stored in the /file/ folder. If not (like if a file under the same name already exists), then it returns an error. So far, it's been working how it's supposed to be.
Okay. So this is what I want done, and I have no idea what to do. Alright. I'm guessing that at some time, someone will want to upload a file that has the same name that a different file already has in my \file\ folder. Is it possible for this script to change the name of the uploading file so that it doesn't have the same name as the file that is already in the folder under the same name?
For example: Yesterday, someone uploaded cool.jpg . Today, someone uploaded cool.php and the script changed the name it was under (in the \file\ directory) to cool-1.jpg .
How can I do this? Thanks!

jatar_k

12:02 pm on Jul 29, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



this is the part you need

move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname

where $newname is where you would put the name of the file.

you might want to look at just uing a timestamp for your files then, that way they won't duplicate, or even better a timestamp combined with some user specific data to ensure uniqueness