Reputation: 13
This is how I store my array of pictures to folder and MySQL rows.
$pictures = array_filter($_FILES['pictures']['name']);
$total_pictures = count($_FILES['pictures']['name']);
for($i = 0; $i < $total_pictures; $i++)
{
$tmpname = $_FILES['pictures']['tmp_name'][$i];
if($tmpname != "")
{
$filepath = $target . $_FILES['pictures']['name'][$i];
if(move_uploaded_file($tmpname, $filepath))
{
$picture_data = Array(
"product_id" => "$product_id",
"picture" => "$pictures[$i]"
);
$insertpicture = $db->insert('products_pictures', $picture_data);
}
}
}
I'm trying to rename my pictures before its uploaded and the name stored to database, but every time I try, I get errors related to string and array conflicts.
Upvotes: 1
Views: 69
Reputation: 5333
You can use this snippet to generate a unique ID everytime and append it to your filename.
substr(md5(microtime(true).mt_Rand()),1,6);
It generates a random string value and strips it to 5 characters for smaller filenames. It uses microtime to get current time, generates a random number based on that and then hashes it with md5.
for($i = 0; $i < $total_pictures; $i++)
{
$tmpname = $_FILES['pictures']['tmp_name'][$i];
if($tmpname != "")
{
$uniqHash = substr(md5(microtime(true).mt_Rand()),1,6); // Generate the 5 char hash
$filepath = $target . $_FILES['pictures']['name'][$i];
if(move_uploaded_file($tmpname, $filepath.$uniqHash)) // Append the hash to $tmpname to make it unique everytime
{
$picture_data = Array(
"product_id" => "$product_id",
"picture" => "$pictures[$i]"
);
$insertpicture = $db->insert('products_pictures', $picture_data);
}
}
}
Upvotes: 1