Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

401
Views
How to Validate File upload only image?

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 ?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

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;
}
about 4 years ago · Juan Pablo Isaza Report

0

  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;
        }
    
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!