troubleshooting Question

incremental naming/numbering of images and thumbnails

Avatar of nascent1
nascent1Flag for Canada asked on
PHP
21 Comments2 Solutions793 ViewsLast Modified:
The code below uploads an image and generates a thumbnail. It works perfectly. (It's from a tutorial I'm working my way through.)

Currently, the names for the image and thumbnail are given random names, such as "809abc8134nfnf98348875fcdfsdfef.jpg" and I would prefer to have the images named incrementally "item1.jpg", "thumb1.jpg", "item2.jpg", "thumb2.jpg", etc.

Can you please explain how I would do that?

function uploadProductImage($inputName, $uploadDir)
{
    $image     = $_FILES[$inputName];
    $imagePath = '';
    $thumbnailPath = '';
   
    // if a file is given
    if (trim($image['tmp_name']) != '') {
        $ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];

        // generate a random new file name to avoid name conflict
        $imagePath = md5(rand() * time()) . ".$ext";
       
        list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);

        // make sure the image width does not exceed the
        // maximum allowed width
        if (LIMIT_PRODUCT_WIDTH && $width > MAX_PRODUCT_IMAGE_WIDTH) {
            $result    = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, MAX_PRODUCT_IMAGE_WIDTH);
            $imagePath = $result;
        } else {
            $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
        }    
       
        if ($result) {
            // create thumbnail
            $thumbnailPath =  md5(rand() * time()) . ".$ext";
            $result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, THUMBNAIL_WIDTH);
           
            // create thumbnail failed, delete the image
            if (!$result) {
                unlink($uploadDir . $imagePath);
                $imagePath = $thumbnailPath = '';
            } else {
                $thumbnailPath = $result;
            }    
        } else {
            // the product cannot be upload / resized
            $imagePath = $thumbnailPath = '';
        }
       
    }

   
    return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 21 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 21 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros