0

I am doing a form that upload multiple images, how do I code such that files that are only 'jpg', 'png', 'gif' will be uploaded successfully and will skip those unacceptable files (eg. doc)? Currently my codes only allow upload if all files are accepted types and will prompt error even if there's only one file that is not acceptable file type

if ($source_type === NULL) {
    echo '<h3>Error</h3><br/>';
    echo 'Invalid file type<br/><br/>';
    echo '<input type="submit" style="color:#000000" onClick="history.go(-1);return true;" value="Back"><br/><br/>';
}
switch ($source_type) {
    case IMAGETYPE_GIF:
        $source_gd_image = imagecreatefromgif($source_file_path);
        break;
    case IMAGETYPE_JPEG:
        $source_gd_image = imagecreatefromjpeg($source_file_path);
        break;
    case IMAGETYPE_PNG:
        $source_gd_image = imagecreatefrompng($source_file_path);
        break;
    default:
        return false;
}

2 Answers 2

1

You can use in_array().

$source_type_allowd = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$source_type        = exif_imagetype($_FILES['file_upload']['tmp_name']);
$error              = !in_array($source_type, $source_type_allowd);// error

exif_imagetype — Determine the type of an image.

Othe option:-

    $mime_type = $_FILES['file_upload']['type'];

    $allowed = array("image/jpeg", "image/gif", "image/png");
    if(!in_array($mime_type, $allowed)) {
      $msg = 'Only jpg, jpeg, and png files are allowed.';
    }else{
      // Upload process
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You can use preg_match() function like this:

$filename = $_FILES['upload_file']['name'];
if(preg_match("/\.(gif|png|jpg)$/", $filename)){
   //file is gif/png/jpg
}
else{
   //invalid file format
   echo 'File should be gif|png|jpg';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.