'How to Validate File upload only image? [duplicate]

I have been able to validate file uploads and only jpg & gif files can be uploaded.

with code like this:

<script>
    function validate() {
    var filename=document.getElementById('file').value;
    var extension=filename.substr(filename.lastIndexOf('.')+1).toLowerCase();
    //alert(extension);
    if(extension=='jpg' || extension=='gif') {
        return true;
    } else {
        alert('Not Allowed Extension!');
        return false;
    }
}
</script>

if I upload a file with the name "tesFile.php.jpg" the file is uploaded successfully. Even though the file is not an image.

How do I validate it with javascript or PHP ?



Solution 1:[1]

You can do it in php with the mime type of the file.

$file = $_FILES['file'];
$mime = get_mime_type($file['tmp_name']); //return eg 'image/png'
//check if mime is valid

function get_mime_type (string $path): string|false {
  if (!function_exists ('finfo_open')) {
    return FALSE;
  }
  if (!$finfo = finfo_open (FILEINFO_MIME_TYPE)) {
    return FALSE;
  }
  $mime_type = finfo_file ($finfo, $path);
  finfo_close ($finfo);
  return $mime_type;
}

Solution 2:[2]

  1. Html with file type validation :

<input type="file" name="myImage" accept="image/png, image/gif, image/jpeg" />
  1. Image type validation in PHP :

    Please refer this link - https://www.w3schools.com/php/php_file_upload.asp

    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

        if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType 
        != "jpeg" && $imageFileType != "gif" ) {
        echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
        $uploadOk = 0;
        }
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lucas
Solution 2 Pream Dev