Victor Adewale
Victor Adewale

Reputation: 43

Upload two different files in the same form

The issue here is, when I Upload videos, it works perfectly but not images which is giving me a hard time to figure out what the error may be


This is what the HTML looks like:

<form action="index.php" method="post" enctype="multipart/form-data" >
   <h1>Browse for file to upload:</h1>
</div>
<div>
    <label for="file"><h1><b>Select Video</b></h1></label>
    <input type="file" name="fileToUpload1[]" id="fileToUpload" >

    <br><br>

    <label for="file"><h2><b>Select Image</b></h2></label>
    <input type="file" name="fileToUpload1[]" id="fileToUpload" >
    <br><br>
    <input type="submit" value="Upload" name="submit">
</form>

The PHP Script looks like this:

$error = null;
$success = null;
$info = [];
$uploadOk = 1;


$allowedMimes = ['video/mp4', 'image/jpg'];

if(isset($_POST["submit"])) {

    $counter = 0;
    foreach ( $_FILES['fileToUpload1']['name'] as $file ):
        $target_file = UPLOAD_DIR . basename($file);
        if ( in_array(mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter]), $allowedMimes) ){
            if (move_uploaded_file($_FILES['fileToUpload1']["tmp_name"][$counter], $target_file)) {
                $info[] = "File ".++$counter."($file) uploaded successfully";
            }else {
                $info[] = "File ".++$counter."($file) cannot be uploaded";
            }
        } else {
            $info[] = "File ".++$counter. " is not allowed.";
        }

    endforeach;    
} else {
    echo "upload a file.";
}


?>


    <ul>
    <?php foreach($info as $i){ ?>
    <li><?=$i;?></li>
    <?php }?>
</ul>
<? } ?>

Upvotes: 1

Views: 102

Answers (1)

Dekel
Dekel

Reputation: 62536

The mimetype of jpg files is actually image/jpeg (and not iamge/jpg), so if you are trying to upload jpg files you should change your $allowedMimes variable to:

$allowedMimes = ['video/mp4', 'image/jpeg'];

Also - if you want to support other image types you can use:

$allowedMimes = ['video/mp4', 'image/png', 'image/jpeg', 'image/gif', 'image/bmp'];

Another option - if you want to support all image/audio/video types you can check only the first part of the string:

$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
    array_shift(
        explode("/", 
            mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
        )
    ),
    $allowedTypes) )

If you are using php>=5.4 you can use:

$allowedTypes = ['video', 'image', 'audio'];
...
if ( in_array(
    explode("/", 
        mime_content_type($_FILES['fileToUpload1']["tmp_name"][$counter])
    )[0],
    $allowedTypes) )

Upvotes: 1

Related Questions