Parameter $_FILES undefined

Asked

Viewed 95 times

0

Good morning, I’m having a problem for some time in a system I’m developing, all CRUD is working perfectly, but when I put a File field to add photo to the register, for some reason ends up showing warning in persistence that the variable was undefined, when it should be.

HTML:

<form method="post" class="form-horizontal form-persistencia" id="form-usuario" action="dao/persistencia.php" enctype="multipart/form-data">
    <? if ($modo == 'edicao') {
        echo '<input type="hidden" name="id" value="<? echo $id; ?>">';
    }?>
    <div class="form-group">
        <label class="control-label">Nível:(*)</label>
        <label><input type="radio" name="nivel" value="admin" id="admin" <? if($modo == 'edicao') { if ($nivel == 'admin') {echo 'checked';} ;} ?>>admin</label>
        <label><input type="radio" name="nivel" value="usuario" id="usuario" <? if($modo == 'edicao') { if ($nivel == 'usuario') {echo 'checked';} ;} ?>>usuario</label>
    </div>

    <div class="form-group">
        <label class="control-label">Nome:(*)</label>
        <input type="text" class="form-control" name="nome" id="nome" autofocus value="<? if($modo == 'edicao') {echo $nome;} ?>">
    </div>

    <div class="form-group">
        <label class="control-label">Login:(*)</label>
        <input type="text" class="form-control" name="login" id="login" value="<? if($modo == 'edicao') {echo $login;} ?>">
    </div>

    <div class="form-group">
        <label class="control-label">Senha:(*)</label>
        <input type="password" class="form-control" name="senha" id="senha" value="">
    </div>

    <div class="form-group">
        <label class="control-label">E-Mail:(*)</label>
        <input type="text" class="form-control" name="email" id="email" value="<? if($modo == 'edicao') {echo $email;} ?>">
    </div>

    <div class="form-group">
        <label class="control-label">Foto:</label>
        <input type="file"  name="foto" id="foto" value="">
    </div>

    <div class="row">
            <div class="col-xs-6 col-sm-6 text-left">
                <a href="Javascript:void(0);" class="btn btn-lg btn-default" onclick="$('#conteudo-formulario').remove();">
                    <span class="glyphicon glyphicon-remove"> Fechar </span>
                </a>
            </div>

            <div class="col-xs-6 col-sm-6 text-right">
                <button disabled type="button" name="submit" id="submit" class="btn btn-lg btn-warning" onclick="verificaFormulario()">
                    <span class="glyphicon glyphicon-ok"> Salvar </span>
                </button>
            </div>
    </div>
    <div id="submeter"></div>
    <input type="hidden" name="id" value="<? if($modo == 'edicao') {echo $id;} ?>">
    <input type="hidden" name="modo" value="<? if($modo == 'edicao') {echo 'edicao';} else if($modo == 'insercao') {echo 'insercao';} ?>">
    <input type="hidden" name="tabela" value="usuario">
</form>

AJAX:

function submeter() {
    $("#form-usuario").ajaxSubmit().data('jqxhr').done(function(data,status,xhr){
      $('#submeter').html(data);
   }).fail(function(err,status,xhr){
      console.log(err);
   });
    $.ajax({
        url: 'dao/persistencia.php',
        type: 'POST',
        data: $('#form-usuario').serialize(),
        mimeType: "multipart/form-data",
        cache: false,
        // contentType: false,
        processData: false,
        success: function(data) {
            $('#submeter').html(data);
            $tabela.bootstrapTable('refresh');
            alert("Usuário cadastrado com sucesso!");
            $formulario[0].reset();
        }
    }); 
}; 

PHP

if ($_POST['modo'] == 'insercao') {
       $img = $_FILES;
       var_dump($img);
      // pegar o nome do arquivo, name é um atributo de vetor que está salvo
      $imgName = $_FILES['foto']['name'];
      $imgTmpName = $_FILES['foto']['tmp_name'];
      $imgSize = $_FILES['foto']['size'];
      $imgError = $_FILES['foto']['error'];
      $imgType = $_FILES['foto']['type'];

      $imgExt = explode('.', $imgName);
      $imgActualExt = strtolower(end($imgExt));

      // informação das extensões permitidas de arquivo
      $permitido = array('jpg', 'jpeg', 'png', 'pdf');

      // se o tipo da imagem está dentro do permitido 
      if (in_array($imgActualExt, $permitido)) {
        // verificar se não tem erros na imagem
        if ($imgError === 0) {
          // se o tamanho do arquivo for menor que 50mb
          if ($imgSize < 50000) {
            $imgNameNew = str_replace(" ", "", strtolower($_POST['nome'])).".".$imgActualExt;
            $imgDestination = '../imagens/imagens_usuario/' . $imgNameNew;
            // Move o arquivo enviado dos arquivos temporarios para o destinatario abaixo
            move_uploaded_file($imgTmpName, $imgDestination);
          } else {
            echo "Tamanho da imagem é maior do que o permitido";
          }
        } else {
          echo "Ocorreu um erro ao fazer upload da imagem!";
        }
      } else {
        echo "Extensão não permitida!";
      }

      $sql = sprintf("INSERT INTO usuario (user_nivel, user_nome, user_login, user_senha, user_email, user_foto) 
                                        VALUES (%s, %s, %s, %s, %s, %s)",
                                    GetSQLValueString($_POST['nivel'], "text"),
                                    GetSQLValueString($_POST['nome'], "text"),
                                    GetSQLValueString($_POST['login'], "text"),
                                    GetSQLValueString(md5($_POST['senha']), "text"),
                                    GetSQLValueString($_POST['email'], "text"),
                                    GetSQLValueString($imgNameNew, "text"));

The error from directly on the line where you declare $img as the "photo file".

  • Everything seems to me in order. But I had a doubt. You don’t have Ubmit boot. How are sending the reports?

  • You are sending the form by ajax?

  • Yes, the button does not have Submit because the form submission is being done by AJAX.

  • Has several questions about this on the site if you still have doubts.

1 answer

0


@aleque_b, sending FILE by ajax does not work equal sending a common form.

Before the body closes and after the jquery include, include the script:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.min.js" integrity="sha384-FzT3vTVGXqf7wRfy8k4BiyzvbNfeYjK+frTVqZeNDFl8woCbF0CYG6g2fMEFFo/i" crossorigin="anonymous"></script>

 <script type="text/javascript">
    $(document).ready(function(){
       $("#form-usuario").ajaxSubmit().data('jqxhr').done(function(data,status,xhr){
          $('#submeter').html(data);
       }).fail(function(err,status,xhr){
          console.log(err);
       });
    });
 </script>

Check the jqueryForm library:

https://github.com/jquery-form/form

  • I pasted this script into a Ready function but still the persistence does not recognize the img field.

  • you placed the parameter action on the form? <form method="post" class="form-horizontal form-persistence" id="form-user" action="dao/persistencia.php" enctype="Multipart/form-data">

  • Why put when you submit the form via AJAX?

  • @aleque_b is how the library works. You can also pass the target URL as parameter in the ajaxSubmit() function, as well as other options. More info -> http://jquery.malsup.com/form/#ajaxSubmit

  • Okay, with the action set for my persistence I was able to send the registration successfully, but two columns are inserted in the database, one with the image and the other not. I believe you are sending 1 as form submission with pure HTML and another by AJAX.

  • update your code in question, please

  • Updated code @Openoak-oak

  • @aleque_b you are sending ajaxSubmit() and then $.ajax again, please remove the second!

  • It worked! It saved me a lot of work time, thank you very much!

  • @aleque_b please signal the answer as correct.

Show 5 more comments

Browser other questions tagged

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