上传图片时无限循环

Infinite loop when uploading image

我想使用浏览按钮上传图片,但是当我点击时,会产生无限循环。我希望加载每个文件,名称为:001 然后 002 然后 003 ...

代码如下:

Index.php

<?php

require('class/Image.php');

if(!empty($_FILES)){
    $image = new Image();
    $images = $image->upload($_FILES);
}
if($images === true){
    $msg_success = 'Le chargement a réussi';
} else {
    $msg_error = 'Le chargement a échoué';
}

?>

<h1>Ajouter une image</h1>

<?php

if(isset($msg_success)){
    echo $msg_success;
}
if(isset($msg_error)){
    echo $msg_error;
}

?>

<form method="post" action="" enctype="multipart/form-data">
    <input type="file" value="" name="upload[]" multiple="multiple">
    <input type="submit" name="uploadFormSubmit" value="Ajouter">
</form>

Image.php

<?php

class Image{

    public function upload($files){

        $upload_dir = '/Applications/MAMP/htdocs/Devoir/PHP/Avancé/1/images/';
        foreach($files['upload']['error'] as $key => $error){
            $error = 0;
            if(!isset($i)){
                $i = 1;
            }
            if($error == UPLOAD_ERR_OK){
                $tmp_name = $files['upload']['tmp_name'][$key];
                $name = $files['upload']['name'][$key]; 
                $tab_name = explode('.', $name);
                $format = '%1d';
                $file_nbr = sprintf($format, $i);
                while(file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
                    $i++;
                }
            }
            if(move_uploaded_file($tmp_name, $upload_dir . $file_nbr . '.' . $tab_name[1]) == false){
                $error += 1;
            }
            if($error == 0){
                return true;
            } else {
                return false;
            }
        }
    }
}

您可能还应该在 while 循环中包含 $file_nbr = sprintf($format, $i);

while (file_exists($upload_dir . $file_nbr . '.' . $tab_name[1])){
    $i++;
    $file_nbr = sprintf($format, $i);
}