Problems sending FILE to Database

3

I'm having a problem sending FILE data to DB. With the help of @zuul I came to this problem.

<?php

require("conectar.php"); //chama o arquivo de conexão ao BD

if (isset($_POST['Nome'])) {
    $Nome = $_POST['Nome'];
}

$Morada = $_POST['Morada'];
$Tipo = $_POST['Tipo'];
$Email = $_POST['Email'];
$AlvaraNumero = $_POST['AlvaraNumero'];
$AlvaraValidade = $_POST['AlvaraValidade'];
$AlvaraAnexo = '';

if (isset($_FILES["AlvaraAnexo"]) && $_FILES["AlvaraAnexo"]["name"] != '') {

    $nomeTemporario = $_FILES["AlvaraAnexo"]["tmp_name"];

    $fp = fopen($nomeTemporario, 'r');
    $AlvaraAnexo = fread($fp, filesize($nomeTemporario));
    $AlvaraAnexo = addslashes($AlvaraAnexo);
    print_r($_FILES);
    fclose($fp);
}

$AcidenteNumero = $_POST['AcidenteNumero'];
$AcidenteValidade = $_POST['AcidenteValidade'];
$AcidenteAnexo = $_POST['AcidenteAnexo'];
$SeguroNumero = $_POST['SeguroNumero'];
$SeguroValidade = $_POST['SeguroValidade'];
$SeguroAnexo = $_POST['SeguroAnexo'];
$FinancasValidade = $_POST['FinancasValidade'];
$FinancasAnexo = $_POST['FinancasAnexo'];
$SocialValidade = $_POST['SocialValidade'];
$SocialAnexo = $_POST['SocialAnexo'];
$RemuneracaoValidade = $_POST['RemuneracaoValidade'];
$RemuneracaoAnexo = $_POST['RemuneracaoAnexo'];
$InstaladorNumero = $_POST['InstaladorNumero'];
$InstaladorValidade = $_POST['InstaladorValidade'];
$InstaladorAnexo = $_POST['InstaladorAnexo'];
$MontadorNumero = $_POST['MontadorNumero'];
$MontadorValidade = $_POST['MontadorValidade'];
$MontadorAnexo = $_POST['MontadorAnexo'];

print_r($_FILES);

$sqlinsert = "INSERT INTO tb_trabalhador  VALUES(0,'" . $Nome . "','" . $Morada . "','" . $Tipo . "','" . $Email . "','" . $AlvaraNumero . "','" . $AlvaraValidade . "','" . $AlvaraAnexo . "', '" . $AcidenteNumero . "', '" . $AcidenteValidade . "','" . $AcidenteAnexo . "','" . $SeguroNumero . "','" . $SeguroValidade . "','" . $SeguroAnexo . "','" . $FinancasValidade . "','" . $FinancasAnexo . "','" . $SocialValidade . "','" . $SocialAnexo . "','" . $RemuneracaoValidade . "','" . $RemuneracaoAnexo . "','" . $InstaladorNumero . "','" . $InstaladorValidade . "','" . $InstaladorAnexo . "','" . $MontadorNumero . "','" . $MontadorValidade . "','" . $MontadorAnexo . "')";
mysql_query($sqlinsert) or die("Não foi possível inserir os dados");
?>

On this line:

print_r($_FILES);   

... the files appear:

Array (
    [AlvaraAnexo] => Array (
        [name] => cc2.pdf
        [type] => application/pdf
        [tmp_name] => C:\wamp\tmp\phpFE7C.tmp
        [error] => 0
        [size] => 153613
    ) 
)
    
asked by anonymous 28.02.2014 / 12:18

1 answer

4

The output of the array $_FILES is exiting with the following information:

Array (
  [AlvaraAnexo] => Array (
    [name]     => cc2.pdf                   // nome do teu ficheiro
    [type]     => application/pdf           // header detectado
    [tmp_name] => C:\wamp\tmp\phpFE7C.tmp   // localização e nome temporário
    [error]    => 0                         // Erro código 0 é o mesmo que tudo correu bem
    [size]     => 153613                    // tamanho do ficheiro
  ) 
)

This tells us that with regards to the HTML form, sending the file and accepting it from the server, everything is going as expected.

If you want to know more about other error codes, you can visit the PHP documentation page: (English) where you can see the various values that you can receive in $_FILES["AlvaraAnexo"]["error"] .

So, we can then pick up your temporary file, read it for a variable and insert it into the database.

This requires a number of verification steps to ensure that everything is done as it is supposed to be. As you are not exactly indicating where your problem might be, I will try to cover all the steps of the process by assuming what I said above (error with code 0 = file uploaded successfully to the server.):

  • Checking the file array

    Before starting operations with the file array, you should check if it is present, if the entry we want exists and if there were no errors:

    // Variáveis de controlo
    $campoForm = "AlvaraAnexo";
    $mensagemErro = "";
    
    // verificar se existe a matriz $_FILES
    if (isset($_FILES)) {
    
      // verificar se existe a entrada com o nome do nosso campo no formulário HTML
      if (isset($_FILES[$campoForm])) {
    
        // verificar se a entrada "error" contém o valor 0
        if ($_FILES[$campoForm]["error"]==0) {
          /* tudo OK, vamos continuar
           */
        } else {
    
          switch($_FILES[$campoForm]["error"]) {
            case 1: {
              $mensagemErro = "O arquivo enviado excede a directiva upload_max_filesize no php.ini.";
              break;
            }
            case 2: {
              $mensagemErro = "O arquivo enviado excede a directiva MAX_FILE_SIZE que foi especificado no formulário HTML.";
              break;
            }
            case 3: {
              $mensagemErro = "O arquivo foi apenas parcialmente carregado.";
              break;
            }
            case 4: {
              $mensagemErro = "Nenhum arquivo enviado.";
              break;
            }
            case 6: {
              $mensagemErro = "Faltando uma pasta temporária.";
              break;
            }
            case 7: {
              $mensagemErro = "Falha ao gravar o arquivo no disco.";
              break;
            }
            case 8: {
              $mensagemErro = "Uma extensão do PHP parou o upload dos arquivos.";
              break;
            }
            default: {
              $mensagemErro = "Erro desconhecido com o código:".$_FILES[$campoForm]["error"];
              break;
            }
          }
        }
      } else {
        $mensagemErro = "Não foi possível encontrar na matriz de ficheiros a entrar para o campo ".$campoForm.".";
      }
    } else {
      $mensagemErro = "Não foi possível encontrar a matriz de ficheiros!";
    }
    
    // verifica se temos erros antes de continuar
    if (!empty($mensagemErro))
      die($mensagemErro);
    
  • Checking the temporary file

    In order to be able to use the file, in your case read the contents of it to the database, we have to check if it exists, if it can be read and if it is not empty:

    // verifica sem temos o caminho e nome do ficheiro
    if (!empty($_FILES[$campoForm]["tmp_name"])) {
    
      $ficheiroTemp = $_FILES["AlvaraAnexo"]["tmp_name"];
    
      // verifica se o ficheiro existe no servidor
      if (is_file($ficheiroTemp)) {
    
        // verifica se o ficheiro pode ser lido
        if (is_readable($ficheiroTemp)) {
    
          /* se chegamos aqui, podemos iniciar a leitura do
           * ficheiro para uma variável e preparar os dados
           * lidos para inserção na base de dados
           */
          $fp = fopen($ficheiroTemp, 'r');
          $AlvaraAnexo = fread($fp, filesize($ficheiroTemp));
          $AlvaraAnexo = addslashes($AlvaraAnexo);
          fclose($fp);
    
        } else {
          $mensagemErro = "O ficheiro não pode ser lido!";
        }
    
      } else {
        $mensagemErro = "Ficheiro temporário não foi localizado no servidor!";
      }
    } else {
      $mensagemErro = "Nome temporário do ficheiro está vazio!";
    }
    
  • Final code

    To make things easier, I wrapped the code that handles the file in a function that returns the result of reading the file or the error found.

    A single function is far from the right way to organize the code, you would need several or even a class to handle the upload of the file, but not to complicate things too much: p>

    /**
     * Ler Ficheiro para Variavel
     * 
     * Ler o conteúdo de um ficheiro temporário
     * que acabou de ser carregado para o servidor
     * para uma variabel de forma a ser guardado
     * na base de dados.
     * 
     * @param array $fileArr            Matriz $_FILES
     * @param string $campoForm         Nome do campo no formulário
     * 
     * @return mix string|array         Matriz com mensagem de erro ou ficheiro
     */
    function lerFicheiroParaVariavel($fileArr, $campoForm = '') {
    
    // Variáveis de controlo
    $mensagemErro = "";
    
        // verificar se existe a matriz $_FILES
        if (isset($fileArr) && is_array($fileArr)) {
    
          // verificar se existe a entrada com o nome do nosso campo no formulário HTML
          if (isset($fileArr[$campoForm])) {
    
            // verificar se a entrada "error" contém o valor 0
            if ($fileArr[$campoForm]["error"]==0) {
              /* tudo OK, vamos continuar
               */
            } else {
    
              $erro = $fileArr[$campoForm]["error"];
    
              switch($erro) {
                case 1: {
                  $mensagemErro = "O arquivo enviado excede a directiva upload_max_filesize no php.ini.";
                  break;
                }
                case 2: {
                  $mensagemErro = "O arquivo enviado excede a directiva MAX_FILE_SIZE que foi especificado no formulário HTML.";
                  break;
                }
                case 3: {
                  $mensagemErro = "O arquivo foi apenas parcialmente carregado.";
                  break;
                }
                case 4: {
                  $mensagemErro = "Nenhum arquivo enviado.";
                  break;
                }
                case 6: {
                  $mensagemErro = "Faltando uma pasta temporária.";
                  break;
                }
                case 7: {
                  $mensagemErro = "Falha ao gravar o arquivo no disco.";
                  break;
                }
                case 8: {
                  $mensagemErro = "Uma extensão do PHP parou o upload dos arquivos.";
                  break;
                }
                default: {
                  $mensagemErro = "Erro desconhecido com o código:".$erro;
                  break;
                }
              }
            }
          } else {
            $mensagemErro = "Não foi possível encontrar na matriz de ficheiros a entrar para o campo ".$campoForm.".";
          }
        } else {
          $mensagemErro = "Não foi possível encontrar a matriz de ficheiros!";
        }
    
    
        // verifica se temos erros antes de continuar
        if (!empty($mensagemErro))
          return array("erro" => $mensagemErro);
    
    
        // verifica sem temos o caminho e nome do ficheiro
        if (!empty($fileArr[$campoForm]["tmp_name"])) {
    
          $ficheiroTemp = $fileArr["AlvaraAnexo"]["tmp_name"];
    
          // verifica se o ficheiro existe no servidor
          if (is_file($ficheiroTemp)) {
    
            // verifica se o ficheiro pode ser lido
            if (is_readable($ficheiroTemp)) {
    
              /* se chegamos aqui, podemos iniciar a leitura do
               * ficheiro para uma variável e preparar os dados
               * lidos para inserção na base de dados
               */
              $fp = fopen($ficheiroTemp, 'r');
              $AlvaraAnexo = fread($fp, filesize($ficheiroTemp));
              $AlvaraAnexo = addslashes($AlvaraAnexo);
              fclose($fp);
    
              return $AlvaraAnexo;
    
            } else {
              $mensagemErro = "O ficheiro não pode ser lido!";
            }
          } else {
            $mensagemErro = "Ficheiro temporário não foi localizado no servidor!";
          }
        } else {
          $mensagemErro = "Nome temporário do ficheiro está vazio!";
        }
    
        // se chegamos aqui é porque temos um erro, vamos devolver o mesmo
        return array("erro" => $mensagemErro);
    }
    

    To use the function, place it at the beginning of your file and apply this code where you are reading the file.

    Where you have:

    if (isset($_FILES["AlvaraAnexo"]) && $_FILES["AlvaraAnexo"]["name"] != '') {
      ...
    }
    

    Delete all% with statment and change it, where you either have an error telling you what happens or you have the if variable containing the contents of the loaded file.

    /* verifica se temos a matriz de ficheiros
     * e se sim procedemos à leitura do ficheiro,
     * caso não recolhemos a mensagem de erro
     */
    if (isset($_FILES)) {
        $ficheiro = lerFicheiroParaVariavel($_FILES, "AlvaraAnexo");
    
        if (is_array($ficheiro)) {
            $mensagemErro = $ficheiro["erro"];
        } else {
            $AlvaraAnexo = $ficheiro;
        }
    } else {
        $mensagemErro = "Não foi possível encontrar a matriz de ficheiros!";
    }
    
    if (!empty($mensagemErro))
        die($mensagemErro);
    

    Note: This handles a file loaded by the $AlvaraAnexo field, but the process must be repeated for all files that are loading.

    Database

    Regarding the database issue, you need to check whether insert queries are occurring, whether the table is well configured and whether the fields are being populated with something:

  • Table structure

    Your fields that receive PDF documents must all be in the name="AlvaraAnexo" format.

    In addition, you have to take into account the size of the data to be saved:

    • blob can be up to 65535 bytes maximum;
    • BLOB can be up to 16777215 bytes maximum;
    • MEDIUMBLOB can be up to 4294967295 bytes maximum.

    A caveat: Storing several LONGBLOB in databases is generally not considered the best idea, as it can cause blob swelling to the table, also having a number of other associated problems.

    The best solution for your case given that you are working with several files would be to move them to a folder and save only the path to them in the database.

  • Insertion query

    You should protect the data that the user gave you before sending them to the database. For this you can use the mysql_real_escape_string (English) to prepare your query:

    // Preparar a consulta de inserção
    $sqlinsert = sprintf(
        "INSERT INTO tb_trabalhador VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')",
        mysql_real_escape_string(null),
        mysql_real_escape_string($Nome),
        mysql_real_escape_string($Morada),
        mysql_real_escape_string($Tipo),
        mysql_real_escape_string($Email),
        mysql_real_escape_string($AlvaraNumero),
        mysql_real_escape_string($AlvaraValidade),
        mysql_real_escape_string($AlvaraAnexo),
        mysql_real_escape_string($AcidenteNumero),
        mysql_real_escape_string($AcidenteValidade),
        mysql_real_escape_string($AcidenteAnexo),
        mysql_real_escape_string($SeguroNumero),
        mysql_real_escape_string($SeguroValidade),
        mysql_real_escape_string($SeguroAnexo),
        mysql_real_escape_string($FinancasValidade),
        mysql_real_escape_string($FinancasAnexo),
        mysql_real_escape_string($SocialValidade),
        mysql_real_escape_string($SocialAnexo),
        mysql_real_escape_string($RemuneracaoValidade),
        mysql_real_escape_string($RemuneracaoAnexo),
        mysql_real_escape_string($InstaladorNumero),
        mysql_real_escape_string($InstaladorValidade),
        mysql_real_escape_string($InstaladorAnexo),
        mysql_real_escape_string($MontadorNumero),
        mysql_real_escape_string($MontadorValidade),
        mysql_real_escape_string($MontadorAnexo)
    );
    
    // tentar inserir dados na base de dados
    mysql_query($sqlinsert) or die("Não foi possível inserir os dados");
    

    Note: For every bloat there should be mysql_real_escape_string in the query. And for each field there must be '%s' . Confirm everything with the fields in your table.

  • 02.03.2014 / 15:07