php - Rename multiple pictures stored in array

one text

Solution:

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);
        }
    }
}

Source