This question already has an answer here:
I am very new with PHP and facing great difficulty. Issue: 1. How to give a unique name to a file to be uploaded. 2. How to save the path in the database.
My code to upload file and save some information in database is:
<?php
$target = "images/"; $target = $target . basename( $_FILES['photo']['name']);
$name=$_POST['name']; $email=$_POST['email']; $phone=$_POST['phone']; $pic=($_FILES['photo']['name']);
mysql_connect("localhost", "admin", "admin") or die(mysql_error()) ;
mysql_select_db ("database") or die(mysql_error()) ;
mysql_query("INSERT INTO `applicants` VALUES ('$name', '$email', '$phone', '$pic')") ;
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
echo "Your application ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been saved";
}
else {
echo "Sorry, there was a problem uploading your resume.";
}
?>
Please help.
</div>
The technique of generating a random number/string and then hashing that with a cheap algorithm is a good practice, but you need to check if that is indeed a unique value:
First generate a random something, and hash it using a cheap algorithm, eg.: md5
$filename = md5(rand() . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 30) . rand());
Even though this seems totally random at first, MD5 is in fact has a not-so-great collision rate. Therefore, I suggest ensuring that this file does not exist yet. A cycle might be good for this case:
for ($i = 0; $i < 1000; $i++) {
# Attempt to generate a unique filename
$filename = md5(rand() . substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 30) . rand());
# We don't have to keep trying if this file does not exist
if (!file_exists("files/$filename.txt")) break;
}
Now you can proceed with whatever operations you want (eg.: inserting this path into a database).
1) There's a lot of different ways to give a file a unique name. You could generate a nasty looking guid http://php.net/manual/en/function.com-create-guid.php Or you could use something like this method as Daan mentioned: md5(microtime().date('d-m-Y H:i:s').$_FILES['file']['name']);
2) Just store the value of the path into a variable and use a simple sql insert to place it in the database. If you want more details you are going to need to post your code.