0

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 ?

2 Answers2

0

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;
}
Lucas
  • 23
  • 3
-1
  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;
        }
    
Pream Dev
  • 19
  • 2
  • It's a good idea to add the `accept` attribute. This will help the user selecting the file but it will actually not protect your app from recieving another file since the web page can easily be changed in the browser with the debugger or with some custom JS. But still, a great idea! I would use `accept="image/*"` since it is relatively compatible now. The server side PHP validation is mendatory but you cannot just do it with the file extension as a user can take any file and rename it. It might be safer to add a second check by trying to open the image and see if you don't get any error. – Patrick Janser May 10 '22 at 09:44