Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

406
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda