K
The matrix output $_FILES is leaving 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 regard to the HTML form, sending the file and accepting it from the server, everything is running as expected.If you want to know more about other error codes, you can visit the PHP documentation page: http://www.php.net/manual/en/features.file-upload.errors.php (English) where the various values you can receive in $_FILES["AlvaraAnexo"]["error"].Therefore, we can then take your file with a given temporary name, read it to a variable and enter the database.This requires a series of verification steps to ensure that everything is being performed as it is supposed to. Since you're not accurately pointing out where your problem might be located, I'll try to cover all steps of the process by assuming what I said above (error with code 0 = file successfully loaded to the server):Check the file matrixBefore we start operations with the file matrix, you should check if the file is present, if the entry we want exists and if there are 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);
Check the temporary fileIn order to be able to use the file, in your case you can 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 codeTo make things easier, I wrapped the code that deals with the file in a function that returns you the file reading result 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 deal with upload of the file, but not to complicate much things:/**
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 to the location you're reading the file.Where you got:if (isset($_FILES["AlvaraAnexo"]) && $_FILES["AlvaraAnexo"]["name"] != '') {
...
}
Erase all the if statment and change for this, where or you have a mistake telling you what's going on or you have the variable $AlvaraAnexo containing the contents of the uploaded 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 deals with a file loaded by the field name="AlvaraAnexo", but the process must be repeated for all files that are being loaded.DatabaseRegarding the issue of the database, you need to check if the insert queries are occurring, if the table is well configured and if the fields are being filled with something:Table structureYour fields that receive PDF documents must all be in format blob.In addition, you must take into account the size of the data to be stored:BLOB can have up to 65535 bytes at most;MEDIUMBLOB can have up to 16777215 bytes at most;LONGBLOB can have up to 4294967295 bytes maximum.A warning: Store several blob in the databases is not generally considered the best idea, since it can cause bloat http://dev.mysql.com/doc/refman/5.1/en/data-size.html (English) to the table, also having a number of other associated problems.The best solution for your case given that you are working multiple files would be to move them to a folder and save only the way for them in the database.Insert queryYou must protect the data that you have given before you send to the database. For this you can make use of http://pt1.php.net/manual/en/function.mysql-real-escape-string.php (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 each mysql_real_escape_string there must be a '%s' in the consultation. And for each field there must be one mysql_real_escape_string. Confirm everything straight with the fields in your table.