image extension check for upload with php

Asked

Viewed 1,674 times

2

Hello, I created a registration page where the user can insert a profile image, everything works normal, except when I check the file extension( I’m new in php) and use this algorithm:

 if(!preg_match("/^image\/(pjpeg|jpeg|png|gif|bmp)$/", $foto["type"])){ 
   $error[1] = "Certifique-se de o arquivo seja uma Imagem!"; 
}

when I remove that line, it works perfectly, what the mistake?
Note: variable that stores the image $photo = $_FILES['pic'];

formCadastro.php

<form action="inserir.php" method="post" enctype="multipart/form-data" name="cadastro" >
   <fieldset >
   <label for="username"><span>Nome</span>
   <input type="text" name="nome" id="username" size="20" class="inputbox" title="Username" /></label>

   <label for="sobrenome"><span>Sobre Nome</span>
   <input type="text" name="sobrenome" id="user_sobrenome" size="20" class="inputbox" title="sobrenome" /></label>

   <label for="password"><span>Senha:</span>
   <input type="password" name="password" id="password" size="20" class="inputbox" title="Password" /></label>

   <label for="datanascimento"><span>Data Nascimento:</span>
   <input type="date" name="datanascimento" id="datanascimento" size="20" class="inputbox" title="datanascimento" /></label>

  <label for="email"><span>Email</span>
  <input type="email" name="email" id="email" size="20" class="inputbox" title="email" /></label>

  <label for="pic"><span>Foto Perfil</span>
  <input type="file" name="pic" id="pic" size="20" class="inputbox" title="pic" /></label>

  <input name="enviar" type="submit" class="button2" value="Logar" />
</fieldset></form>

insert.php

<?php
error_reporting(E_WARNING);//Odeio Warning X-X
$conn = @mysql_connect("localhost", "root", "") or die ("Conection Error!"); 
$database = @mysql_select_db("me", $conn) or die ("Conection Error!");

if($_POST['enviar']){
    $passwordUsuario = md5($_POST['password']);
    $emailUsuario = $_POST['email'];
    $nomeUsuario = $_POST['nome'];
    $sobreNome = $_POST['sobrenome'];
    $dataNascUsuario = date('Y-m-d', strtotime($_POST['datanascimento']));
    $foto = $_FILES['pic'];

    //verifica se a imagem foi selecionada e o tamanho do arquivo
        if(!empty($foto['name'])){
            $largura = 256;//Teste!
            $altura = 256;//Teste!
            $tamanho = 300000;//teste!

        //Verifica Tipo de arquivo enviado
        if(!preg_match('/^îmage\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $foto['type'])){
            $error[1] = " Verifique o tipo do Arquivo! ";
        }

        //Armazena dimenssões da Imagem
        $dimenssoes = getimagesize ($foto["tmp_name"]);

        //$largura maxima da Imagem
        if($dimenssoes[0] > $largura){
            $error[2] = "A largura não deve ultrapassar ".$largura."px!";
            }

        //$altura maxima da Imagem
        if($dimenssoes[1] > $altura){
            $error[3] =  "A altura não deve ultrapassar ".$altura."px!";
            }

        //$tamanho Maximo da Imagem
        if($foto["size"] > $tamanho){
            $error[4] = "A imagem deve ter no maximo ".$tamanho." bytes.";
            }

        //Sem  erros
        if(count($error) == 0){

            //Pega extensão da imagem
            preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $foto['name'], $ext);

            //Gera id para Imagem
            $nome_imagem = md5(uniqid(time())) . "." . $ext[1];

            //diretório da foto
            $caminho_imagem = "fotos/" . $nome_imagem;

            //Envia a imagem para o diretorio fotos/
            move_uploaded_file($foto["tmp_name"], $caminho_imagem);

            //insere os dados no banco
            $sql = mysql_query("INSERT INTO users VALUES ('', '".$passwordUsuario."' , '".$emailUsuario."' , '".$nomeUsuario."' , '".$sobreNome."' ,  '".$dataNascUsuario."' , '".$foto."')");  

            //Se não ouver erro GG!
            if($sql){
                    echo 'Bem vindo!';
                }
            }

            //se ouver erro ¬.¬)
            if(count($error) !=0){
                foreach ($error as $erro){
                        echo $erro . "<br />";
                }
            }
        }
    }

?>

  • what mistake you’re having?

  • the check is ok, you must be having trouble in some other part of the code, could post the full code to take a look?

  • This check seems correct. Some error appears?

  • yes! @Lucas "Check File Type!" Does it work perfectly when I remove this line, register normally, more when I put to check, he error, has another way to prevent sending by extension? I don’t have much knowledge in php, I’m studying some basic functions only

1 answer

3


I don’t know for sure, but it seems your code is with I invalid.

// errado
if (!preg_match('/^îmage\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $foto['type'])) {
    echo 'errado';
}

// certo
if (!preg_match('/^image\/(pjpeg|jpeg|png|gif|bmp|jpg)$/', $foto['type'])) {
    echo 'certo';
}

Another observation. Your code is super insecure. Search about mysql Injection And if you’re learning, get started right, using some PDO library or PDO itself. http://br.phptherightway.com/ a good read to get started.

  • really! was that right that little guy "|" but that key is next to the right left shift? is it the keyboard? thank you very much! when the PDO did not understand much, I will take a look..

  • 1

    Yeah, writing code sometimes warms the mind. a silly mistake makes us spend hours trying to find what it is. How that character got into i don’t know, haha. About PDO, it helps prevent sql Injection. In this your current code someone badly intensioda can use the input name to send sql commands. Which may result in you losing all your content, showing data that user n should see, editing your content without your permission.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.