How do I limit the extensions that can be saved? (PHP)

0

Hi, I was able to run the code and save the file, but I want you to save only images. Without the filter it saves any kind of file. How could it make only the jpg, jpeg and png extensions be saved? Below the code

<form action="proc_artigos.php" method="post" enctype="multipart/form-data">
        <div class="form-group"> 
            <label for="">Título</label>
            <input class="form-control" type="text" name="titulo" required>
        </div>

        <div class="form-group">
            <label for="">Imagem</label>
            <input type="file" name="imgUpload">
        </div>

        <div class="form-group">      
            <label for="">Conteúdo</label>
            <textarea class="form-control" type="text" name="texto" rows="30" required ></textarea>
            </div>
                <input name="send" class="btn btn-primary btn-block" type="submit" value="Salvar">                      
       </form>

File php:

if ($_SERVER["REQUEST_METHOD"] === "POST") {

$file = $_FILES["imgUpload"];

if ($file["error"]) {
    throw new Exception("Error: " . $file["error"]);
}

$dirUploads = "uploads";

if (!is_dir($dirUploads)) {
    mkdir($dirUploads);
}

if (move_uploaded_file($file["tmp_name"], $dirUploads . DIRECTORY_SEPARATOR . $file["name"])) {

} else {
    throw new Exception("Não foi possível salvar o arquivo.");

  }
}

Thank you!  Note: The rest is working, I just want to limit the extensions of the files that can be saved.

    
asked by anonymous 17.12.2018 / 18:30

3 answers

1

By Front-end you can use:

 <input type="file" accept="image/*">

or

 <input type="file" accept=".png, .jpg, .jpeg">

and Back-end:

<?php
$arquivo = "imagem.exe";
$imagem = ".jpg";
$video = ".mp4";
$virus = ".exe";

if (substr($arquivo, -4) === $imagem) {
    echo "É imagem";
}elseif (substr($arquivo, -4) == $video) {
    echo "É vídeo";
}elseif (substr($arquivo, -4) == $virus) {
    echo "É virus";
}else{
    echo "Não sei! :-/";
}

?>
    
17.12.2018 / 19:15
0

you do as follows at the top of the page add:

ini_set('gd.jpeg_ignore_warning', 1);

This does not display a warning when the image is corrupted or the file type is not identified.

Dai validate this way:

if ((exif_imagetype($ImagePathAndName) == IMAGETYPE_JPEG) && (imagecreatefromjpeg( $ImagePathAndName ) !== false ))
{
echo 'è um jpg<br>';
}
    
17.12.2018 / 18:39
0

From what I understand you want to analyze an IMAGE. So you can use getimagesize() to see if it's really an image. For it will return false if it is any other file. Then you can implement the extensions that can be used:

if(($testeImage = getimagesize($file["tmp_name"])) != false){

    $exts = ["image/gif", "image/jpeg", "image/png", "image/bmp"];

    if(in_array($testeImage['mime'], $exts)){
        echo "imagem válida";
    }
}

In my opinion, this is a more secure solution.

    
17.12.2018 / 19:43