I would like to upload multiple images to my server using this code:

<html>
<body>



<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input id="picture_01" name="userfile['01']" tabindex="auto" type="file">
<input id="picture_02" name="userfile['02']" tabindex="auto" type="file">
  <input id="picture_03" name="userfile['03']" tabindex="auto" type="file">
<input id="picture_04" name="userfile['04']" tabindex="auto" type="file">
<input id="picture_05" name="userfile['05']" tabindex="auto" type="file">
<input id="picture_06" name="userfile['06']" tabindex="auto" type="file">  
<input type="submit" name="submit" value="Submit">
</form>

</body>
</html>

and the upload_file.php

 <?php

$foldername = "anotherfolder";

$userfile = array(
            '01' => 'hello',
            '02' => 'bye',
            '03' => 'likka',
            '04' => 'pippa',
            '05' => 'laptop',
            '06' => 'cow06',
            '07' => 'cow07',
            '08' => 'cow08',
            '09' => 'cow09',
            '10' => 'cow10',            
            );

            echo $userfile ['01'];

foreach ($userfile as $keys => $values); 

//Upload Images
$success = 0;
$fail = 0;
$uploads_dir = "temp_images";
$count = 1;
foreach ($_FILES["userfile"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["userfile"]["tmp_name"][$key];
        $name = $_FILES["userfile"]["name"][$key];
        $uploadfile = "$uploads_dir/$name";
        $ext = strtolower(substr($uploadfile,strlen($uploadfile)-3,3));
        if (preg_match("/(jpg|gif|png|bmp|jpeg)/",$ext)){
            $newfile = "$uploads_dir/"."$values".".".$ext;
            if(move_uploaded_file($tmp_name, $newfile)){
                           }else{
                echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
            }
        }else{
            echo "Invalid Extension.\n";
            $fail++;
        }
    }
}

?>

I would like that when someone uploads the first picture in the first input it is renamed to 'hello', if it is uploaded in the second input it is renamed to 'bye'. If two pictures are uploaded the first picture is named 'hello' and the second picture renamed to 'bye'.

I tried to look for a solution but I wasn't successful. I can't understand what is wrong. The files are being named sequentially 'cow10' the latest value in the array regardless of which input the picture is uploaded from.

Any help or suggestions?

Dani AI

Generated

Quick diagnosis: the immediate cause of every file being renamed to the same value is that the mapping loop in your script is effectively empty — a stray semicolon or similar bug leaves the loop body skipped so the mapping variable ends up as the last element. Also check the HTML input names: using quotes inside the bracket (for example name="userfile['01']") produces unexpected keys in PHP. Use array-style names without embedded quotes (either indexed like userfile[01] or the simpler userfile[]) and make sure your mapping keys match the actual keys PHP creates.

Two practical options

  • Let PHP build a simple numeric array by using userfile[] in the form, then map names by order (first file → first map entry). This is what suggested.
  • Keep associative keys, but write them correctly in the HTML (no inner quotes) and ensure your mapping array uses the exact same keys.

Debugging checklist

  • Put a var_dump($_FILES) and var_dump($map) at the top of the upload handler to confirm keys.
  • Remove the stray semicolon after your mapping foreach.
  • Ensure the temp_images folder exists and is writable.
  • Verify PHP limits (upload_max_filesize, post_max_size) if uploads silently fail.

Minimal, safer handling (example)

$map = ['01'=>'hello','02'=>'bye','03'=>'likka'];
$allowed = ['jpg','jpeg','png','gif','bmp'];

foreach ($_FILES['userfile']['tmp_name'] as $k => $tmp) {
    if (empty($tmp) || !is_uploaded_file($tmp)) continue;
    $ext = strtolower(pathinfo($_FILES['userfile']['name'][$k], PATHINFO_EXTENSION));
    if (!in_array($ext, $allowed)) continue;
    $base = isset($map[$k]) ? $map[$k] : "file_$k";
    $safe = preg_replace('/[^A-Za-z0-9_-]/', '_', $base);
    move_uploaded_file($tmp, "temp_images/$safe.$ext");
}

Notes: use pathinfo() (not fixed-length substr) for extensions, validate image MIME (finfo or getimagesize) if security matters, and add a unique suffix when you must avoid overwrites.

I suggest simple keep name tag as following for all file input elements, do not give number in html form. This way you will get file upload array in upload_file.php. you can user var_dump to see how file array is built. Accordingly you can write your code.

name="userfile[]" ;//correct

name="userfile['01']" ; not good practice

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.