Some notes again (mainly for myself) but maybe it'll help someone.
Problem:
Create a form that (after inserting data into a database) takes a file and uploads it to the server after renaming it with the timestamp, auto_incremented id, and a value from one of the fields from the mysql insert. (heh. Still with me?)
Solution:
First, in your form, to get one of those fields with the "browse" button next to it that prompts you with a "file locating dialog thingy":
<input name="filename" type="file" size="40">
Let's assume you set up your table with one field as an auto increment id table key. After running the insert query, you can do this to get the id of that last insert:
mysql_insert_id();
When we include the value from one of the fields in the form (lets say the field is "username"), we have to remove all the spaces before we upload it. So we do this:
str_replace(' ', ", $HTTP_POST_VARS['username']);
Now lets create the name of the file to be uploaded, which will look like tablekeyid_username_timestamp.ext
$uploaddir = '/path/to/upload/dir/';
$ext = strstr($_FILES['filename']['name'], ".");
// that "['name']" part does not change
// however ['filename'] does
// (filename was the name of the file input field.
// For more information about that $_FILES thing go here
// By doing the above I'm making sure I keep the same
// extension to the filename.
$username = str_replace(' ', ", $HTTP_POST_VARS['username']);
$idnum = mysql_insert_id();
$newfilename = $idnum."_".$username."_".time().$ext;
// time() gets the current time as a unix time stamp.
if (move_uploaded_file($_FILES['filename']['tmp_name'], $uploaddir . $newfilename)) {
echo "File uploaded!";
} else {
echo "File upload failed.";
}
Update: As Kyle reminded me, one of the things that you have to include in the form tag to get a file upload to work is this:
method='post' enctype="multipart/form-data"
So your form tag looks something like:
<form name="sendfile" method="post" action="sendfile.php" onSubmit="return validate();" enctype="multipart/form-data">
Just a side note here, the text in italics above is whatever you set it to. Also, that onSubmit="return validate()" – I'll have to make a post about that at some point – validating your forms, but in short, validate is a function that I defined that goes through the form and checks each field for apporpriate content. If it goes through okay, it simply ends with "return"… if there's something wrong with the form, I throw up an "alert" with an explanation of what's wrong, and then a "return false"… but there will be a more in-depth post about that to come…