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?
– Karl Zillner
You are sending the form by ajax?
– Diego Vieira
Yes, the button does not have Submit because the form submission is being done by AJAX.
– Alex Borgmann
Has several questions about this on the site if you still have doubts.
– Woss