I'm experiencing a problem in my code. I know that i'm doing something wrong, but I don't know what.
I have a photo upload form and it have to create a folder if it doesn't exist already, and upload the picture to that folder. 

So my problem is that **I can't do both at the same tim**e.
If the folder already exist the image is uploaded, but if the folder don't exist, it only create the folder and I have to do another upload for that picture goes into that folder.

Here is my code.

**INDEX.HTML**

```
<form action="" method="post" enctype="multipart/form-data">
<input id="input-image-3" class="file-loading" type="file" id="file" name="files[]" multiple="multiple" accept="image/*" />
</form>

        <script>
        $("#input-image-3").fileinput({
            uploadUrl: "upload.php",
            allowedFileExtensions: ["jpg","jpeg", "png", "gif"],
            maxImageWidth: 100,
            maxImageHeight: 100,
            resizePreference: 'height',
            maxFileCount: 10,
            resizeImage: true,

        }).on('filepreupload', function() {
            $('#kv-success-box').html('');
        }).on('fileuploaded', function(event, data) {
            $('#kv-success-box').append(data.response.link);
            $('#kv-success-modal').modal('show');
        });

        </script>

```

**UPLOAD.PHP**

```
<?php
$valid_formats = array("jpg", "png");
$max_file_size = 1024*100; //100 kb
$path = "up/test/"; // Upload directory, later i'll get the name of user
$filename=$file['filename'];
$extension = '.jpg';
$i=1;
while(file_exists($path.$filename.$extension)){
                  $filename=$file['filename']."teste_($i)";
                 $i++;}

if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
    // Loop $_FILES to exeicute all files
    foreach ($_FILES['files']['name'] as $f => $name) { 
        if ($_FILES['files']['error'][$f] == 4) {
            continue; // Skip file if any error found
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if ($_FILES['files']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue; // Skip large files
            }
            elseif( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue; // Skip invalid file formats
            }
            else{ // No error found! Move uploaded files

                    if(!is_dir($path)){mkdir($path, 0755);} // If dont exist, create folder

                move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$filename.$extension);    
            }    
        }
    }
}
echo json_encode (json_decode ("{}"));
?>

```

Thank you in advance,