0

I have a form that had a file type input to upload images, but it would always show up the "notice: undefined index" and I saw that the $_FILE was coming empty, but none of the answers that I found online have helped me.

I have a project where after the user registers he has to login and his first page he confirms his data and insert some new ones, one of this new ones is a picture that he can upload, as I said, my initial problem was that the $_FILES was always coming up empty, I searched online and this is a fairly common error but none of the answers have helped me, after a lot of trying I found out what the problem is, but I still have no Idea why, or how to fix it.

At the start of the page that I talked about there's this bit off code here:

     if(isset($_SESSION['logado'])){
        $dados =  $_SESSION['dadosUsu'];
     }else{
        unset($_SESSION['dadosUsu']);
        session_destroy();
        header("Location: homeLandingPage.php");
     }

to stop unnauthorized people into the page or create a variable with the user data so that it can be used to fill out some of the inputs with the info that the user had already registered.

I found that if I removed this bit off code, the $_FILES global started working and the code runned fine, but if the code was there the problems continued, I have no ideia why this is happening and I couldn't find anything online that talk about a session conflicting with the $_FILES global.

after that there's this bit of ajax:

     $(function(){
         $('.form').submit(function(){
             $.ajax({
               url: 'cod_alterarAcc.php',
               type: 'POST',
               data: $('.form').serialize(),
               success: function(data){
                   if(data != ''){
                      $('.recebeDados').html(data);
                      document.getElementById('visor1').value = '<?= $dados['nomeUsu']; ?>';
                      document.getElementById('visor2').value = '<?= $dados['emailUsu']; ?>';
                      document.getElementById('visor3').value = '<?= $dados['emailUsu']; ?>';
                      document.getElementById('visor4').value = '';
                      document.getElementById('visor5').value = '';
                      document.getElementById('visor6').value = '';
                    }
                 }
              });
            return false;
         });
      });

I don't know if it's this but here it's the preview function that is called onChange on the input type file:

     function previewImagem() {
         var imagem = document.querySelector('input[name=img]').files[0];
         var preview = document.querySelector('img[id=dup]');

         var reader = new FileReader();

         reader.onloadend = function () {
             preview.src = reader.result;
         }

         if (imagem) {
             reader.readAsDataURL(imagem);
         } else {
             preview.src = "";
         }
     }

here is the form that Im using:

    <form enctype="multipart/form-data" class='form' method='post' action='cod_alterarAcc.php'>
      <div id="img-perfil">
         <img src="imagens/perfil.png"  id="dup"/>
         <label for="selecao-arquivo" class="selecionar-img">+</label>
         <input id="selecao-arquivo" type="file" name="img" class="botao-img" onchange="previewImagem()" />
      </div>

      <label>Confirme seu nome:</label>
      <input type="text" id="visor1" name="nome_usu" value="<?= $dados['nomeUsu']; ?>" />

       <label>Altere seu email:</label>
       <input type="email" id="visor2" name="email" value="<?= $dados['emailUsu']; ?>" />

       <label>Confirme seu email:</label>
       <input type="email" id="visor3" name="confirmaEmail" value="<?= $dados['emailUsu']; ?>" />   

       <label>Sua senha:</label>
       <input type="password" id="visor4" name="senha" />

       <label>Confirme sua senha:</label>
       <input type="password" id="visor5" name="confirmaSenha" />

       <label>Insira seu cpf:</label>
       <input type="text" id="visor6" name="cpf_usu" />

       <div class='recebeDados'></div>
       <input type="submit" value="confirmar" />
    </form>  

on the cod_alterarAcc.php page has some validations using filter_input_array() and then I have this:

    $extensao = strtolower(substr($_FILES['img']['name'], -4));
    $novo_nome = sha1(time()) . $extensao;
    $diretorio = "imgsBanco/";
    $ext =  strtolower(substr($_FILES['img']['name'], -3));
    $tipos = array("png","jpg","gif");
    $imagem = $diretorio.$novo_nome;

I have some more validation regarding the other inputs and then this, it's the first time that I use the session in this page:

  if (in_array($ext, $tipos)) {
      if (move_uploaded_file($_FILES['img']['tmp_name'], $imagem)) { 

        $codAcesso = $_SESSION['dadosUsu']['codAcesso'];
        $codUsu = $_SESSION['dadosUsu']['codUsu'];
        $senhaEncript = Bcrypt::hash($infoPost['senha']);

after that I do an update on everything in the database, including the image url which is the $imagem variable, after that I only look at the session one more time to send the user to another page depending on it's user type.

I've also tested for most of the possibilities in here Why would $_FILES be empty when uploading files to PHP? and it didn't worked

Like I said, apparently the only thing that it's messing with the $_FILES it's that part where I use the session on the first page, if someone could help me fix this problem and explain why it's happening in the first place I would appreciate it a lot.

  • 2
    Commonly $_SESSION don't interact with the $_FILE, there might something you have done wrong outside the code you showed. – Francis G Sep 13 '19 at 04:03
  • 1
    Tell us the exact error you are getting.... – Ropali Munshi Sep 13 '19 at 04:08
  • Do a print_r($_FILES['img']) and look at the error entry. The could be something in the php.ini settings preventing the upload. If the value for $_FILE['img']['error'[ is not zero then the value of the number can be found at https://www.php.net/manual/en/features.file-upload.errors.php –  Sep 13 '19 at 04:10
  • @Francisaskquestion I have the code page for this form return some information about errors and things like that through AJAX and put them in the that empty div and a preview function in javascript to show the image onChange, could one of that be the source problem? – Moisés S. Oliveira Sep 13 '19 at 04:16
  • @jeff I did the print_r($_FILES['img']) and it gave me the "Notice: Undefined index: img", after that I removed that bit of code I metioned ealier and it returned Array ( [name] => KeepClamandLoveProgramming.png [type] => image/png [mp_name] => C:\wamp64\tmp\php6D84.tmp [error] => 0 [size] => 85047 ) – Moisés S. Oliveira Sep 13 '19 at 04:30
  • I simply cannot say that it might be one of those, but certainly like I said that you might have done something, can you show all results and codes regarding to your test? – Francis G Sep 13 '19 at 05:08

1 Answers1

0

It seems that the default action of the form is conflicting with your AJAX, but if you want to use only AJAX in uploading your file then you want to prevent the default action of the form. Your AJAX request should be look like this.

$('.form').submit(function(e){
    e.preventDefault();    // Preventing the default action of the form
    var formData = new FormData(this); // So you don't need call serialize()

    $.ajax({
        url: 'cod_alterarAcc.php',
        type: 'POST',
        data: formData,
        success: function (data) {
            if(data != ''){
                $('.recebeDados').html(data);
                document.getElementById('visor1').value = '<?= $dados['nomeUsu']; ?>';
                document.getElementById('visor2').value = '<?= $dados['emailUsu']; ?>';
                document.getElementById('visor3').value = '<?= $dados['emailUsu']; ?>';
                document.getElementById('visor4').value = '';
                document.getElementById('visor5').value = '';
                document.getElementById('visor6').value = '';
            }
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

also put your form into FormData and specify your ajax request type.

EDIT

Try to confirm if PHP able to get the data with

print_r($_POST);
print_r($_FILES);

And in your AJAX success function

console.log(data);

EDIT

Forgot to put the parameter e on form.submit

Francis G
  • 1,040
  • 1
  • 7
  • 21