Problems with PHP upload

Asked

Viewed 278 times

0

I have an upload system, where the client publishes PDF files on the site. Files below 10MB is fine, but when the file is above 10MB, the system is at 92% and does not upload. See:

inserir a descrição da imagem aqui

I contacted the server and they informed that the limit is 128MB. I was in doubt, because if the system uploads files below 10MB, why above 10MB it stops at 92% and does not generate any error or error logs on the server? See below the code:

HTML

    <form action="#" method="post" enctype="multipart/form-data">                       

                      <div class="form-group">
                        <label for="titulo">Título: </label>
                        <input id="titulo" class="form-control" name="Titulo" placeholder="" type="text">
                      </div>
                      <div class="form-group">
                       <label for="periodo">Período:</label>
                            <div class="input-group col-md-3">                        
                              <input id="periodo" class="form-control" name="PeriodoInicio" placeholder="" type="text" data-inputmask="'mask' : '99/99/9999'">
                              <span class="input-group-addon">à</span> 
                              <input id="periodo" class="form-control" name="PeriodoFinal" placeholder="" type="text" data-inputmask="'mask' : '99/99/9999'">
                          </div>
                      </div>
                      <div class="row">
                          <div class="form-group">
                            <div class="col-md-12">
                             <label for="ano">Ano:</label>
                           </div>
                            <div class="col-md-3">
                            <input id="ano" class="form-control" name="AnoEdicao" placeholder="Ex.: <?php echo date("Y"); ?>" type="text" maxlength="4" data-inputmask="'mask' : '9999'">
                          </div>
                          </div>
                      </div>
                      <div class="form-group" style="margin-top: 10px">
                       <label for="arquivo">Arquivo:</label>
                        <input type="file" id="arquivo" name="Arquivo" class="form-control" style="cursor: pointer">
                      </div>
                      <div class="form-group">
                        <label class="col-sm-2 control-label"></label>
                        <div class="col-sm-12">
                                <div class="progress progress-striped active">
                                        <div class="progress-bar" style="width: 0%">
                                        </div>
                                </div>
                        </div>
                    </div> 
                    <div align="center">
                        <button id="send" type="submit" class="btn btn-primary"><i class="fa fa-floppy-o fa-lg" aria-hidden="true"></i> Salvar</button>
                      </div>
                    </form>

<script>
    $(document).on('submit', 'form', function (e) {
            e.preventDefault();
            //Receber os dados
            $form = $(this);        
            var formdata = new FormData($form[0]);

            //Criar a conexao com o servidor
            var request = new XMLHttpRequest();

            //Progresso do Upload
            request.upload.addEventListener('progress', function (e) {
                    var percent = Math.round(e.loaded / e.total * 100);
                    $form.find('.progress-bar').width(percent + '%').html(percent + '%');
            });

            //Upload completo limpar a barra de progresso
            request.addEventListener('load', function(e){
            $form.find('.progress-bar').addClass('progress-bar-success').html('upload completo...');
            //Atualizar a página após o upload completo
            setTimeout("window.open(self.location, '_self');", 1000);
            });

            //Arquivo responsável em fazer o upload da imagem
            request.open('post', 'processar-cadastro-edicoes.php');
            request.send(formdata);
            console.log(formdata);
    });
</script>

PHP

public function cadastrarEdicoes($arquivo,$temp,$titulo,$periodoInicio,$periodoFinal,$anoEdicao){

      $sqlVerificar = mysqli_query($this->conexao,"SELECT * FROM pf_edicoes WHERE Titulo = '".$titulo."' AND PeriodoInicio = '".mysqli_real_escape_string($this->conexao,$periodoInicio)."' AND PeriodoFinal = '".mysqli_real_escape_string($this->conexao,$periodoFinal)."' AND anoEdicao = '".mysqli_real_escape_string($this->conexao,$anoEdicao)."';");

      if(mysqli_num_rows($sqlVerificar) > 0){
           $_SESSION["CadastroExistente"] = time() + 3; // Verifica se o arquivo e o período já está cadastrado      
      }else{
        $extensao = pathinfo($arquivo, PATHINFO_EXTENSION);

           if($extensao != "pdf"){
              $_SESSION["ErroExtensao"] = time() + 3; // Verifica se a extensão é pdf
           }else{   
              $antigo = umask(0);
              $criarDiretorio = mkdir("../../arquivos/".$anoEdicao,0777); 
              umask($antigo);
              $diretorio = "../../arquivos/".$anoEdicao;

              list($nomeArquivo,$extensaoArquivo) = explode(".".$extensao,$arquivo);
              $codArquivo = md5(date("d-m-Y H:i:s").$nomeArquivo).".".$extensao;

                if(move_uploaded_file($temp,$diretorio."/".$codArquivo)){
                   $cadArquivo = "arquivos/".$anoEdicao."/".$codArquivo;
                   $sqlCadastrar = mysqli_query($this->conexao,"INSERT INTO pf_edicoes VALUES(null,'0','".mysqli_real_escape_string($this->conexao,$titulo)."','".mysqli_real_escape_string($this->conexao,$periodoInicio)."','".mysqli_real_escape_string($this->conexao,$periodoFinal)."','".mysqli_real_escape_string($this->conexao,$cadArquivo)."','".mysqli_real_escape_string($this->conexao,$anoEdicao)."')");

                   if(mysqli_affected_rows($this->conexao) > 0){

                      $idEdicao = mysqli_insert_id($this->conexao);
                      mysqli_query($this->conexao,"UPDATE pf_edicoes SET IdCodEdicoes = '".md5(strrev($idEdicao))."' WHERE IdEdicoes = '".$idEdicao."';");

                      $_SESSION["Sucesso"] = time() + 3;
                      return "<script>window.location.href='cadastrar-edicoes.php';</script>";
                   }else{
                      $_SESSION["ErroCadastro"] = time() + 3; // Erro no cadastro
                   }   

                }else{
                   $_SESSION["ErroUpload"] = time() + 3; // Erro no uplado
                } 
            }
        }
    } 

I honestly don’t know where the bug is. Whether it’s on our side or the server side.

PHP configuration on the server:

inserir a descrição da imagem aqui

  • It can be php configuration in post size. Problem with uploading large files in PHP

  • Hello rray. I made a change to my post. I included the full code HMTL and Jquery, and the image of the PHP configuration on the server. I confess that I am really in doubt if the problem is ours or the server’s. If there are no errors on our part, I will return to the server with arguments for them to check there.

1 answer

1


The lock can be on post_max_size or in the upload_max_filesize, a very important detail, after editing the PHP.INI or the PHPRC you need to restart the HTTP server (and/or fastcgi if you are using something as a reverse proxy).

However Apache also locks to limit the size of the payload.

Maybe the Apache or some .htaccess is being blocked by LimitRequestBody or else:

  • LimitRequestFields
  • LimitRequestFieldSize
  • LimitRequestLine

Or it can if any other problem that just looking at the browser console to know what fault occurred, may even be a fault in your local network.

If it is a fault in the local network, something that I have suffered several times, then there is no way to solve with programming or with servers, maybe the best is totally change approach, in case I recommend even to improve the response time on the server when there are multiple sessions is to partition the upload using the API:

However riding from scratch I understand that it is something complex, which will require to know better HTTP and know better the Apis and behaviors between different browsers, as it seems that you already use jQuery so I recommend a library ready to https://github.com/blueimp/jQuery-File-Upload

On the link https://github.com/blueimp/jQuery-File-Upload/wiki/Chunked-file-uploads is explained as partitioning, for example:

$('#fileupload').fileupload({maxChunkSize: 1000000}) //Divide de um 1 MB por vez
    .on('fileuploadchunksend', function (e, data) {})
    .on('fileuploadchunkdone', function (e, data) {})
    .on('fileuploadchunkfail', function (e, data) {})
    .on('fileuploadchunkalways', function (e, data) {});
  • Hello William. When we disabled the wi-fi from here and tried directly with the portable wi-fi from my smartphone, the upload was successful. What could this be? Problems with our Wi-Fi service provider or some impediment to our IP with the server? This is the first time I’ve been through this.

  • The problem is that even if it is a problem on the local network other users may have the same problem, I will post an alternative solution, maybe it is better

  • @Fox.11 edited the answer, see if this lib helps you

  • 1

    Hi William. Right. I will test the Jquery File Upload you have passed. Thank you.

Browser other questions tagged

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