Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

402
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda