Notice: Undefined index in variable $ _FILES (PHP upload) [closed]

2

I created this code to add products to my database, but an error occurs in the image, says that I did not define it.

The code is this:

<?php   
ob_start();
session_start();
require 'ligarDb.php';


$error = false;
$nameError ="";
$imagem ="";


 if(isset($_POST['btn-add'])){ 


        $nameP = trim($_POST['nameP']);// o trim elimina espaços na string 
        $nameP = strip_tags($nameP);// Retira as tags HTML e PHP de uma string
        $nameP = htmlspecialchars($nameP);// Converte caracteres especiais para a realidade HTML

        $preco = trim($_POST['preco']);
        $preco = strip_tags($preco);
        $preco = htmlspecialchars($preco);

        $size = trim($_POST['size']); 
        $size = strip_tags($size);
        $size = htmlspecialchars($size); 

        $estado = trim($_POST['estado']);
        $estado = strip_tags ($estado);
        $estado = htmlspecialchars($estado);

        $cor = trim($_POST['cor']);
        $cor = strip_tags($cor);
        $cor = htmlspecialchars($cor);

        $descricao = trim($_POST['descricao']);
        $descricao = strip_tags($descricao);
        $descricao = htmlspecialchars($descricao);

        $imagem  = $_FILES['foto']['name'];
        $img_dir = $_FILES['foto']['tmp_name'];
        $imgSize = $_FILES['foto']['size'];


 //validação do Nome Produto

    if(empty($nameP)){
                 $error = true;
                 $nameError = "Preencha o nome.";
    }else if (strlen($nameP) < 3) {
                 $error = true;
                 $nameError = "Nome tem de ter mais caracteres.";
    } else if (empty($imagem)) {
                $error = true;
                $imgError = "Por favor selecione uma imagem.";
    } else {

        $upload_dir = '../upload/'; //diretório onde será guardada a imagem.
        $imgExt = strtolower(pathinfo($imagem, PATHINFO_EXTENSION));
    //validação de extensao 

        $valid_ext = array('jpeg','jpg','png');
    // 
        $user_pic = rand(1000,1000000)." . ".$imgExt;

    // valida os formatos das imagens
        if(in_array($imgExt, $valid_ext)){
            //verifica se o tamanho é de 5MB
            if($imgSize < 5000000 ){
                move_uploaded_file($img_dir,$upload_dir.$user_pic);
            } else {
                $imgError = "Desculpa, a sua imagem é muito grande.";
            }
        }  else {
            $imgError = "Desculpe, apenas extesões JPG, JPEG, PNG.";
        }

    }

 if(!$error){  

$addnew = mysqli_query($ligacao, "INSERT INTO products (nomeP,preco,estado,tamanho,cor,descricao, imagem) VALUES ('$nameP','$preco','$estado','$size','$cor','$descricao', '$user_pic')");

    if($addnew) {
          $errTyp = "successo";
          $errMSG = "Registrado com sucesso.";
          header('refresh: 10; form_addnew.php');
              unset($nameP);
              unset($preco);
              unset($size);
              unset($estado);
              unset($cor);
              unset($descricao);
              unset($user_pic);
   } else {
    $errTyp = "Erro";
    $errMSG = "Tem algo errado, tente mais tarde..."; 
   } 

  }
}

?>

 <!--começa o formulario-->
    <?php include('header.php'); ?>

        <div class="grid">
            <div class="col-2-3">
                <form id="my-login-form" method="post" action="" enctype=”multipart/form-data”>
                    <div class="form-group">
                        <h2 class="">Adicionar novo / <a href="mySnoop.php">Voltar</a></h2>   
                    </div>



   <!--abriu o php $errMSG-->   <?php
              if (isset($errMSG)){ 
            ?>
                        <div class="form-group">
                            <div class="alert alert-<?php echo ($errTyp=="successo ") ? "success0 " : $errTyp; ?>"> <span class="glyphicon"></span>
                                <?php echo $errMSG; ?>
                            </div>
                        </div>
                        <?php  } ?> <!--fechou o php $errMSG-->


                            <!--tabelas d formulario-->
                            <div class="form-group required">
                                <div class="input_something">
                                    <label for="">Nome:</label>
                                    <input type="text" name="nameP" required placeholder="" value="" /></div> <span class="text-danger"><?php echo $nameError; ?></span> 
                            </div>


                            <div class="form-group required">
                                <div class="input_something">
                                    <label for="">Categoria:</label>
                                    <input type="text" name="" required placeholder="" value="" /></div> <span class="text-danger"><?php echo $nameError; ?></span> 
                            </div>


                            <div class="form-row required">
                                <div class="input_something">
                                    <label for="">Preço:</label>
                                    <input type="text" name="preco"   placeholder="" value="" required /> </div>
                                <span class="text-danger">
                                </span>
                            </div>

                            <div class="form-row required">
                                <div class="input_something">
                                    <label for="">Tamanho:</label>
                                    <input type="text" name="size"   placeholder="" value="" required /> </div>
                                    <span class="text-danger"></span> 
                            </div>

                            <div class="form-row required">
                                <div class="input_something">
                                    <label for="">Estado:</label>
                                    <input type="text" name="estado"  placeholder="" value="" required /></div>
                                    <span class="text-danger"></span> 
                            </div>

                             <div class="form-row required">
                                <div class="input_something">
                                    <label for="">Cor:</label>
                                    <input type="text" name="cor"  placeholder=" " value="" required /></div>
                                    <span class="text-danger"></span> 
                            </div>

                              <div class="form-row required">
                                <div class="input_something">
                                    <label for="">Descrição:</label>
                                    <textarea type="text" name="descricao"  placeholder="" value="" required/></textarea></div>
                                    <span class="text-danger"></span> 
                            </div>

                            <div class="form-group required">
                                <div class="input_something">
                                    <label for="">Imagem:</label>
                                    <input  name="foto" type="file" placeholder="" value=""/></div> <span class="text-danger"> </span> 
                            </div><br>

                                 <input name="btn-add" type="submit" value="Registrar" />
                            <!-- botao entrar-->
                </form>

            </div>
            <div class="col-1-4"><img src="imgs/publicidade.png"></div>
        </div>

<?php include('footer.php'); ?>
<?php ob_end_flush(); ?>

The error that appears is this:

  

Notice: Undefined index: photo in C: \ xampp \ htdocs \ snoop \ form_addnew.php   on line 39 Notice: Undefined index: foto in   C: \ xampp \ htdocs \ snoop \ form_addnew.php on line 40 Undefined   index: photo in C: \ xampp \ htdocs \ snoop \ form_addnew.php on line 41

    
asked by anonymous 21.03.2017 / 13:06

1 answer

3

The only error I encountered in your code was in the section below, where enctype = multipart / form-data is not with " (quotation marks) correctly.

This attribute must be entered in form for file upload to work. What was happening is that because of the wrong quotation marks it was not being recognized, as shown in the code below.

<form id="my-login-form" method="post" action="" enctype=”multipart/form-data”>

Please correct the excerpt by putting the quotation marks as below and check if it worked:

<form id="my-login-form" method="post" action="" enctype="multipart/form-data">

Reference: PHP 5 File Upload

    
21.03.2017 / 17:25