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


<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">


and the upload_file.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)){
                echo "Couldn't move file: Error Uploading the file. Retry after sometime.\n";
            echo "Invalid Extension.\n";


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?

4 Years
Discussion Span
Last Post by urtrivedi

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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.