When I upload files I use PHP's unique_id() function for the filename that is stored on the server (and I preserve the file extension since it makes it easier for me when I am looking at all the files in the storage directory via the local file system).
I save the file outside of the website file system (aka you can never browse directly to the files).
I always use php's move_uploaded_file() function to save the file to the server.
I store the original filename, the path/filename where it is stored, and any other project related information you might need about who uploaded it, etc in a database.
In some of my implementations I also create a hash of the file contents and save that in the database too. Then with other uploaded files look in the database to see if I have a copy of that exact file already stored.
Some code examples:
The form:
form method="post" enctype="multipart/form-data" action="your_form_handler.php">
<input type="file" name="file1" value="" />
<input type="submit" name="b1" value="Upload File" />
</form>
The form handler:
<?php
// pass the file input name used in the form and any other pertinent info to store in the db, username in this example
_process_uploaded_file('file1', 'jsmith');
exit;
function _process_uploaded_file($file_key, $username='guest'){
if(array_key_exists($file_key, $_FILES)){
$file = $_FILES[$file_key];
if($file['size'] > 0){
$data_storage_path = '/path/to/file/storage/directory/';
$original_filename = $file['name'];
$file_basename = substr($original_filename, 0, strripos($original_filename, '.')); // strip extention
$file_ext = substr($original_filename, strripos($original_filename, '.'));
$file_md5_hash = md5_file($file['tmp_name']);
$stored_filename = uniqid();
$stored_filename .= $file_ext;
if(! move_uploaded_file($file['tmp_name'], $data_storage_path.$stored_filename)){
// unable to move, check error_log for details
return 0;
}
// insert a record into your db using your own mechanism ...
// $statement = "INSERT into yourtable (original_filename, stored_filename, file_md5_hash, username, activity_date) VALUES (?, ?, ?, ?, NOW())";
// success, all done
return 1;
}
}
return 0;
}
?>
Program to handle download requests
<?php
// Do all neccessary security checks etc to make sure the user is allowed to download the file, etc..
//
$file = '/path/to/your/storage/directory' . 'the_stored_filename';
$filesize = filesize($file);
header('Content-Description: File Transfer');
header("Content-type: application/forcedownload");
header("Content-disposition: attachment; filename=\"filename_to_display.example\"");
header("Content-Transfer-Encoding: Binary");
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header("Content-length: ".$filesize);
ob_clean();
flush();
readfile("$file");
exit;
If you want to present the download in the same page that the user is requesting it from then look at my answer to this post: Dowloading multiple PDF files from javascript