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

Asked

Viewed 695 times

2

I created this code to add products to my database, only that there is an error in the image, says I did not set 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 presented is this:

Notice: Undefined index: foto 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 Notice: Undefined index: photo in C: xampp htdocs Snoop form_addnew.php on line 41

  • 1

    Jolene, could enter the error that occurred as well?

  • Notice: Undefined index: foto 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 Notice: Undefined index: foto in C: xampp htdocs Snoop form_addnew.php on line 41

  • is referring to that part of the code $image = $_FILES['photo']['name']; //39 $img_dir = $_FILES['photo']['tmp_name']; // 40 $imgSize = $_FILES['photo']['size']; // 41

  • Jolene, the ideal is to put the error in the question by editing it. But I already put the error there, so you can leave.

  • William solved this way... $image = isset($_FILE['photo']['name']), so now it does not register in the database :(

  • Jolene, you actually solved the mistake. The error happens because this data referring to the upload of the photo for some reason is not being saved and it tries to access a data that does not exist. now it just doesn’t save the die. but that data still doesn’t show up. I’ll try to check the reason here and answer.

  • Thank you William

Show 2 more comments

1 answer

3


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

The insertion of this attribute in the form to make the file upload work. What was happening is that because of the wrong quotes he was not being recognized, as excerpt below in his code.

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

Please correct the excerpt by quotation marks according to the section below and make sure it worked:

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

Reference:
PHP 5 File Upload

  • obrgado William, that’s right, I just replaced the high commas with quotes.

  • Jolene, feel free to mark my answer as the right one. I’m glad it helped you! = D

  • >>> http://answall.com/q/50988/3635 :)

  • @Guilhermenascimento in her case the error is different.

  • But they are very similar

  • It is true, I had not noticed, strange those quotes, until I know usually only if you type something by msword or similar they appear, she must have copied the code from somewhere without paying attention.

  • @Guilhermenascimento I believe it was just that.

Show 2 more comments

Browser other questions tagged

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