Search code examples
phparraysloopsfile-uploadmkdir

Wrong location of conditional statements. Because of loop everything is destroyed, using multi upload files


This application creates a new folder every time a new files are uploaded and insert these files inside the created folder. The code below works fine but Im a bit confused. Because of multiple uploading I can not check if something was uploaded or not and I lose a control with the created folder, because it is created even if I do not upload files (only submit the form). Why is that the folder is created when I only submit form? Because the "UPLOAD_ERR_OK" is checking the form after the folder is crated (first is "mkdir" and after "UPLOAD_ERR_OK" (but it have to be this way, because of loop ([$i]!))). What I want to do is to put UPLOAD_ERR_OK at the start, but i can not, because it must contains an array [$i]! In a single upload "if ($_FILES['img']['error'] == UPLOAD_ERR_OK)" works fine, but does not in multi , because of the array.

The script below has stages:

  1. create folder
  2. if files havent errors
  3. upload files to folder

It is wrong, because the folder is created at the start even if we upload empty form and the form is checked after, so it creates a folder and make error "UPLOAD_ERR_NO_FILE". But it is impossible to first check errors and then create folder, because arrors are checking with an array after loop.

if (!file_exists($pre_path)) // if no folder
{
    if (mkdir($pre_path, 0777)) // create folder
    {
        for ($i=0; $i < count($_FILES['img']['name']) $i++) //LOOP
        {
            if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK) //if no error
            {
                //MOVE UPLOADED FILES[$i], QUERIES AND FUNCTIONS
            }
            elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { }//show error
            elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) {} //show error
            elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { } //show error
            elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) {}  //show error
            elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { } //show error
            elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { } //show error
            elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { }//show error
            else { }//show error
        }
    }
}

I want it to be like: 1. if files havent errors (was not "UPLOAD_ERR_NO_FILE") 2. create folder 3. upload files to folder

if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK)
{
if (mkdir($pre_path, 0777))
{
    for ($i=0; $i < count($_FILES['img']['name']) $i++)
    {
        //MOVE UPLOADED FILES[$i], QUERIES AND FUNCTIONS
    }
}
}
elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { }//show error
elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) {} //show error
elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) {}  //show error
elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { } //show error
elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { }//show error
else { }//show error

What should I do to put "if ($_FILES['img']['error'][$i] == UPLOAD_ERR_OK)" with the [$i] array at the start and to create a folder after errros are checked? We cannot put mkdir inside the loop, because loop will create many folders. What do I need is only 1 folder, so it must be before the loop. :/ That's crazy. Full code:

if (isset($_SESSION['admin'], $_POST['upload_images']))
{
    $img_tmp_name = $_FILES['img']['tmp_name'];
    $img_name = $_FILES['img']['name'];
    $img_error = $_FILES['img']['error'];
    $img_type = $_FILES['img']['type'];
    $img_size = $_FILES['img']['size'];

    $image_quantity = count($img_name);

    $error_text = array (
        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
        3 => 'The uploaded file was only partially uploaded',
        4 => 'No file was uploaded',
        6 => 'Missing a temporary folder',
        7 => 'Failed to write file to disk.',
        8 => 'A PHP extension stopped the file upload.',
        9 => 'file couldnt be moved!',
        10 => 'file isnt uploaded',
        11 => 'za duzy rozmiar pliku',
        12 => 'obrazek musi byc w formacie JPEG',
        13 => 'nie mozna stworzyc folderu',
        14 => 'Query has not started, but folder has created with number: ',
        15 => 'Unknown upload error'
    );

    $conn = lacz_bd();

    if ($q = $conn->prepare('SELECT MAX(gallery_id) FROM galleries'))
    {
        $q->execute();
        $q->bind_result($gallery_id);
        $q->store_result();

        while($q->fetch())
        {
            $improved_gallery_id = $gallery_id + 1;
        }

        $pre_path = ('./galerie/'.$improved_gallery_id);

        //------------------------------- START UPLOAD ----------------------------------   

        if (!file_exists($pre_path))
        {
            if (mkdir($pre_path, 0777))
            {
                for ($i=0; $i < $image_quantity; $i++)
                {
                    if ($img_error[$i] == UPLOAD_ERR_OK)
                    {
                        if ($img_type[$i] = 'image/jpeg') //to do: preg match instead
                        {
                            if ($img_size[$i] <= 2621440) //2,5MiB
                            {
                                if (is_uploaded_file($img_tmp_name[$i]))
                                {
                                    $path = $pre_path.'/'.basename($img_name[$i]);

                                    if (move_uploaded_file($img_tmp_name[$i], $path))
                                    {
                                        if ($q = $conn->prepare('INSERT INTO galleries (path, gallery_id) VALUES (?, ?)'))
                                        {
                                            $q->bind_param('si', $path, $improved_gallery_id);
                                            $q->execute();

                                            if ($q->affected_rows > 0)
                                            {
                                                image_compression($path, 800, 536);

                                                echo '<a href="ustaw_miniature.php?m='.urlencode($img_name[$i]).'&gid='.urlencode($improved_gallery_id).'">';
                                                echo '<img src="'. htmlspecialchars($path, ENT_QUOTES).'" width="80%" height="80%"></img></a><br />';                    
                                            }
                                        }
                                    } else { echo $error_text[9]; }
                                } else { echo $error_text[10]; }
                            } else { echo $error_text[11]; }
                        } else { echo $error_text[12]; }
                    }
                    elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { echo $error_text[1]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) { echo $error_text[2]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { echo $error_text[3]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) { echo $error_text[4]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { echo $error_text[6]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { echo $error_text[7]; }
                    elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { echo $error_text[8]; }
                    else { echo $error_text[15]; }
                } // END FOR
            }

        } else { echo $error_text[14].' '.htmlspecialchars($improved_gallery_id, ENT_QUOTES);}

        $q->free_result();
        $q->close();
    }
    $conn->close();
}

I am sitting at the computer and waiting for help. Thanks. It is important for me, because I make a site for developer.


Solution

  • You can reorganise your conditionals so it checks and creates the folder only on the first loop $i == 0. You will need to check and probably change the error message $error_text[14] in the below example of one way to change your conditionals.

    if (isset($_SESSION['admin'], $_POST['upload_images']))
    {
        $img_tmp_name = $_FILES['img']['tmp_name'];
        $img_name = $_FILES['img']['name'];
        $img_error = $_FILES['img']['error'];
        $img_type = $_FILES['img']['type'];
        $img_size = $_FILES['img']['size'];
    
        $image_quantity = count($img_name);
    
        $error_text = array (
            1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
            2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
            3 => 'The uploaded file was only partially uploaded',
            4 => 'No file was uploaded',
            6 => 'Missing a temporary folder',
            7 => 'Failed to write file to disk.',
            8 => 'A PHP extension stopped the file upload.',
            9 => 'file couldnt be moved!',
            10 => 'file isnt uploaded',
            11 => 'za duzy rozmiar pliku',
            12 => 'obrazek musi byc w formacie JPEG',
            13 => 'nie mozna stworzyc folderu',
            14 => 'Query has not started, but folder has created with number: ',
            15 => 'Unknown upload error'
        );
    
        $conn = lacz_bd();
    
        if ($q = $conn->prepare('SELECT MAX(gallery_id) FROM galleries'))
        {
            $q->execute();
            $q->bind_result($gallery_id);
            $q->store_result();
    
            while($q->fetch())
            {
                $improved_gallery_id = $gallery_id + 1;
            }
    
            $pre_path = ('./galerie/'.$improved_gallery_id);
    
            //------------------------------- START UPLOAD ----------------------------------   
    
    
            for ($i=0; $i < $image_quantity; $i++)
            {
                if ($img_error[$i] == UPLOAD_ERR_OK)
                {
                    if ($img_type[$i] = 'image/jpeg') //to do: preg match instead
                    {
                        if ($img_size[$i] <= 2621440) //2,5MiB
                        {
                            if (is_uploaded_file($img_tmp_name[$i]))
                            {
                                if ($i == 0) // only the first loop create directory
                                {
                                    if (!file_exists($pre_path) && !is_dir($pre_path))
                                    {
                                        if (mkdir($pre_path, 0777))
                                        {
                                            // todo: handle the error
                                            exit();
                                        }
                                    }
                                }
                                if (is_dir($pre_path))
                                {
                                    $path = $pre_path.'/'.basename($img_name[$i]);
    
                                    if (move_uploaded_file($img_tmp_name[$i], $path))
                                    {
                                        if ($q = $conn->prepare('INSERT INTO galleries (path, gallery_id) VALUES (?, ?)'))
                                        {
                                            $q->bind_param('si', $path, $improved_gallery_id);
                                            $q->execute();
    
                                            if ($q->affected_rows > 0)
                                            {
                                                image_compression($path, 800, 536);
    
                                                echo '<a href="ustaw_miniature.php?m='.urlencode($img_name[$i]).'&gid='.urlencode($improved_gallery_id).'">';
                                                echo '<img src="'. htmlspecialchars($path, ENT_QUOTES).'" width="80%" height="80%"></img></a><br />';                    
                                            } // end affected_rows
                                        } // end prepare
                                    } // end move_uploaded_file
                                    else { echo $error_text[9]; }
                                } // end is_dir
                                else { echo $error_text[14].' '.htmlspecialchars($improved_gallery_id, ENT_QUOTES);}
                            } // end is_uploaded_file
                            else { echo $error_text[10]; }
                        } // end image size
                        else { echo $error_text[11]; }
                    } // end image type
                    else { echo $error_text[12]; }
                } // end error check
                elseif ( $img_error[$i] == UPLOAD_ERR_INI_SIZE) { echo $error_text[1]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_FORM_SIZE) { echo $error_text[2]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_PARTIAL) { echo $error_text[3]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_NO_FILE) { echo $error_text[4]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_NO_TMP_DIR) { echo $error_text[6]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_CANT_WRITE) { echo $error_text[7]; }
                elseif ( $img_error[$i] == UPLOAD_ERR_EXTENSION) { echo $error_text[8]; }
                else { echo $error_text[15]; }
            } // end for loop
    
            $q->free_result();
            $q->close();
        } // end prepare
        $conn->close();
    } // end isset