上传图片时无限循环

时间:2015-04-08 11:03:09

标签: php loops printf infinite

我想使用浏览按钮上传图片,但是当我点击时,会产生无限循环。我想要加载每个文件,名称是: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 = '%1$03d';
                $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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

你可能也应该在你的while循环中加入$file_nbr = sprintf($format, $i);

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