Jump to content


Photo

Problema Com Upload De Imagem


  • Faça o login para participar
1 reply to this topic

#1 vilao

vilao

    12 Horas

  • Usuários
  • 195 posts
  • Sexo:Não informado

Posted 22/05/2008, 11:27

Galera

To tentando fazer uma pagina que irá adicionar um nome ao banco e jogar uma imagem pra determinada pasta, realizar um upload.

Até agora ela ta funcionando 50%. Ela envia corretamente o nome da imagem e formato pro banco certim, ex: "foto.jpg" mas não faz o upload pra pasta que eu determinei.

Usei o dreameaver pra fazer o insert no banco.
Usei um tutorial pra fazer o upload

Eis o resultado:


PHP

<?php 


require_once('Connections/flatshop.php'); 




function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;

  switch ($theType) {
	case "text":
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
	  break;	
	case "long":
	case "int":
	  $theValue = ($theValue != "") ? intval($theValue) : "NULL";
	  break;
	case "double":
	  $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
	  break;
	case "date":
	  $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
	  break;
	case "defined":
	  $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
	  break;
  }
  return $theValue;
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "adicionar")) {



/********************************/
/*	 INICIO UPLOAD DA IMAGEM 	*/
/********************************/





$erro = $config = array();

// Prepara a variável do arquivo
$arquivo = isset($_FILES["foto"]) ? $_FILES["foto"] : FALSE;

// Tamanho máximo do arquivo (em bytes)
$config["tamanho"] = 106883;
// Largura máxima (pixels)
$config["largura"] = 1000;
// Altura máxima (pixels)
$config["altura"]  = 1000;

// Formulário postado... executa as ações
if($arquivo)
{  
	// Verifica se o mime-type do arquivo é de imagem
	if(!eregi("^image\/(pjpeg|jpeg|png|gif|bmp)$", $arquivo["type"]))
	{
		$erro[] = "Arquivo em formato inválido! A imagem deve ser jpg, jpeg, 
			bmp, gif ou png. Envie outro arquivo";
	}
	else
	{
		// Verifica tamanho do arquivo
		if($arquivo["size"] > $config["tamanho"])
		{
			$erro[] = "Arquivo em tamanho muito grande! 
		A imagem deve ser de no máximo " . $config["tamanho"] . " bytes. 
		Envie outro arquivo";
		}
		
		// Para verificar as dimensões da imagem
		$tamanhos = getimagesize($arquivo["tmp_name"]);
		
		// Verifica largura
		if($tamanhos[0] > $config["largura"])
		{
			$erro[] = "Largura da imagem não deve 
				ultrapassar " . $config["largura"] . " pixels";
		}

		// Verifica altura
		if($tamanhos[1] > $config["altura"])
		{
			$erro[] = "Altura da imagem não deve 
				ultrapassar " . $config["altura"] . " pixels";
		}
	}
	
	// Imprime as mensagens de erro
	if(sizeof($erro))
	{
		foreach($erro as $err)
		{
			echo " - " . $err . "<BR>";
		}

		echo "<a href=\"foto.html\">Fazer Upload de Outra Imagem</a>";
	}

	// Verificação de dados OK, nenhum erro ocorrido, executa então o upload...
	else
	{
		// Pega extensão do arquivo
		preg_match("/\.(gif|bmp|png|jpg|jpeg){1}$/i", $arquivo["name"], $ext);

		// Gera um nome único para a imagem
		$imagem_nome = md5(uniqid(time())) . "." . $ext[1];

		// Caminho de onde a imagem ficará
		$imagem_dir = "fotos/" . $imagem_nome;

		// Faz o upload da imagem
		move_uploaded_file($arquivo["tmp_name"], $imagem_dir);

   }
}





/********************************/
/*	 FINAL UPLOAD DA IMAGEM 	*/
/********************************/



  $insertSQL = sprintf("INSERT INTO imoveis (tipo, titulo, descricao, caracteristicas, quartos, endereco, municipio, bairro, foto, mapa, destaque, negocio, titulo2, descricao2, caracteristicas2, endereco2) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
					   GetSQLValueString($_POST['tipo'], "text"),
					   GetSQLValueString($_POST['titulo'], "text"),
					   GetSQLValueString($_POST['descricao'], "text"),
					   GetSQLValueString($_POST['caracteristicas'], "text"),
					   GetSQLValueString($_POST['quartos'], "text"),
					   GetSQLValueString($_POST['endereco'], "text"),
					   GetSQLValueString($_POST['municipio'], "text"),
					   GetSQLValueString($_POST['bairro'], "text"),
					   GetSQLValueString($_POST['foto'], "text"),
					   GetSQLValueString($_POST['mapa'], "text"),
					   GetSQLValueString($_POST['destaque'], "int"),
					   GetSQLValueString($_POST['negocio'], "text"),
					   GetSQLValueString($_POST['titulo2'], "text"),
					   GetSQLValueString($_POST['descricao2'], "text"),
					   GetSQLValueString($_POST['caracteristicas2'], "text"),
					   GetSQLValueString($_POST['endereco2'], "text"));

  mysql_select_db($database_flatshop, $flatshop);
  $Result1 = mysql_query($insertSQL, $flatshop) or die(mysql_error());

  $insertGoTo = "imoveis.php";
  if (isset($_SERVER['QUERY_STRING'])) {
	$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
	$insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_flatshop, $flatshop);
$query_qMunicipios = "SELECT * FROM municipio";
$qMunicipios = mysql_query($query_qMunicipios, $flatshop) or die(mysql_error());
$row_qMunicipios = mysql_fetch_assoc($qMunicipios);
$totalRows_qMunicipios = mysql_num_rows($qMunicipios);

mysql_select_db($database_flatshop, $flatshop);
$query_qBairro = "SELECT * FROM bairro";
$qBairro = mysql_query($query_qBairro, $flatshop) or die(mysql_error());
$row_qBairro = mysql_fetch_assoc($qBairro);
$totalRows_qBairro = mysql_num_rows($qBairro);

mysql_select_db($database_flatshop, $flatshop);
$query_qNegocios = "SELECT * FROM negocio";
$qNegocios = mysql_query($query_qNegocios, $flatshop) or die(mysql_error());
$row_qNegocios = mysql_fetch_assoc($qNegocios);
$totalRows_qNegocios = mysql_num_rows($qNegocios);

mysql_select_db($database_flatshop, $flatshop);
$query_qQuartos = "SELECT * FROM quartos";
$qQuartos = mysql_query($query_qQuartos, $flatshop) or die(mysql_error());
$row_qQuartos = mysql_fetch_assoc($qQuartos);
$totalRows_qQuartos = mysql_num_rows($qQuartos);

mysql_select_db($database_flatshop, $flatshop);
$query_qTipo = "SELECT * FROM tipo";
$qTipo = mysql_query($query_qTipo, $flatshop) or die(mysql_error());
$row_qTipo = mysql_fetch_assoc($qTipo);
$totalRows_qTipo = mysql_num_rows($qTipo);
?>


HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<? include 'includes/head.php'; ?>
<style type="text/css">
<!--
.style3 {font-size: 10px; font-family: Verdana, Arial, Helvetica, sans-serif; }
.style4 {color: #006600}
-->
</style>
<body>
<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
	<td><img src="imagens/topo-login.jpg" width="700" height="60" /></td>
  </tr>
  <tr>
	<td> </td>
  </tr>
  <tr>
	<td><img src="imagens/curva01.gif" width="700" height="25" /></td>
  </tr>
  <tr>
	<td bgcolor="#FFFFFF"><? include 'includes/menu-principal.php'; ?></td>
  </tr>
  <tr>
	<td><img src="imagens/curva02.gif" width="700" height="25" /></td>
  </tr>
  <tr>
	<td> </td>
  </tr>
  <tr>
	<td><img src="imagens/curva01.gif" width="700" height="25" /></td>
  </tr>
  <tr>
	<td bgcolor="#FFFFFF"><table width="98%" border="0" align="center" cellpadding="0" cellspacing="0">
	  <tr>
		<td width="26%" valign="top">
		
		<? include 'includes/menu-imoveis.php'; ?>		</td>
		<td width="74%" valign="top"><table width="95%" border="0" align="right" cellpadding="0" cellspacing="0">
		  <tr>
			<td height="32" class="menu-borda"><div align="right" id="thumbs"><a href="inicial.php">Principal</a> >> <a href="imoveisMunicipios.php">Imóveis</a> </div></td>
		  </tr>
		  <tr>
			<td><form id="adicionar" name="adicionar" method="POST" action="<?php echo $editFormAction; ?>">
			  <table width="100%" border="0" cellspacing="3" cellpadding="5">
				<tr>
				  <td height="25" background="imagens/filete-topo.png" class="style3">Cadastramento de Imóvel </td>
				</tr>
				<tr>
				  <td><table width="100%" border="0" align="center" cellpadding="3" cellspacing="5">
					  <tr>
						<td height="50" colspan="2" bgcolor="#EEEEEE" class="style3"><label>Atenção: Preencha corretamente todos os campos! Inclusives os disponíveis para o segundo idioma (ingles). </label></td>
					  </tr>
					  <tr>
						<td width="32%" height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Titulo</div></td>
						<td width="68%"><input name="titulo" type="text" class="form" id="titulo" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Titulo (EN)) </div></td>
						<td><input name="titulo2" type="text" class="form" id="titulo2" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Descrição</div></td>
						<td><input name="descricao" type="text" class="form" id="descricao" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Descrição (EN) </div></td>
						<td><input name="descricao2" type="text" class="form" id="descricao2" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Cadacteristicas</div></td>
						<td><input name="caracteristicas" type="text" class="form" id="caracteristicas" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Caracteristicas (EN) </div></td>
						<td><input name="caracteristicas2" type="text" class="form" id="caracteristicas2" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Municipio</div></td>
						<td><label>
						  <select name="municipio" class="form" id="municipio" style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<?php
do {  
?>
							<option value="<?php echo $row_qMunicipios['titulo']?>"><?php echo $row_qMunicipios['titulo']?></option>
							<?php
} while ($row_qMunicipios = mysql_fetch_assoc($qMunicipios));
  $rows = mysql_num_rows($qMunicipios);
  if($rows > 0) {
	  mysql_data_seek($qMunicipios, 0);
	  $row_qMunicipios = mysql_fetch_assoc($qMunicipios);
  }
?>
						  </select>
						</label></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Bairro</div></td>
						<td><select name="bairro" class="form" id="bairro"  style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<?php
do {  
?>
							<option value="<?php echo $row_qBairro['titulo']?>"><?php echo $row_qBairro['titulo']?></option>
							<?php
} while ($row_qBairro = mysql_fetch_assoc($qBairro));
  $rows = mysql_num_rows($qBairro);
  if($rows > 0) {
	  mysql_data_seek($qBairro, 0);
	  $row_qBairro = mysql_fetch_assoc($qBairro);
  }
?>
						</select></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Endereço</div></td>
						<td><input name="endereco" type="text" class="form" id="endereco" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Endereço (EN) </div></td>
						<td><input name="endereco2" type="text" class="form" id="endereco2" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Negocio</div></td>
						<td><select name="negocio" class="form" id="negocio"  style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<?php
do {  
?>
							<option value="<?php echo $row_qNegocios['titulo']?>"><?php echo $row_qNegocios['titulo']?></option>
							<?php
} while ($row_qNegocios = mysql_fetch_assoc($qNegocios));
  $rows = mysql_num_rows($qNegocios);
  if($rows > 0) {
	  mysql_data_seek($qNegocios, 0);
	  $row_qNegocios = mysql_fetch_assoc($qNegocios);
  }
?>
						</select></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Quartos</div></td>
						<td><select name="quartos" class="form" id="quartos"  style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<?php
do {  
?>
							<option value="<?php echo $row_qQuartos['titulo']?>"><?php echo $row_qQuartos['titulo']?></option>
							<?php
} while ($row_qQuartos = mysql_fetch_assoc($qQuartos));
  $rows = mysql_num_rows($qQuartos);
  if($rows > 0) {
	  mysql_data_seek($qQuartos, 0);
	  $row_qQuartos = mysql_fetch_assoc($qQuartos);
  }
?>
						</select></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Tipo</div></td>
						<td><select name="tipo" class="form" id="tipo"  style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<?php
do {  
?>
							<option value="<?php echo $row_qTipo['titulo']?>"><?php echo $row_qTipo['titulo']?></option>
							<?php
} while ($row_qTipo = mysql_fetch_assoc($qTipo));
  $rows = mysql_num_rows($qTipo);
  if($rows > 0) {
	  mysql_data_seek($qTipo, 0);
	  $row_qTipo = mysql_fetch_assoc($qTipo);
  }
?>
						</select></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Foto</div></td>
						<td><input name="foto" type="file" class="form" id="foto" size="30" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Mapa</div></td>
						<td><input name="mapa" type="text" class="form" id="mapa" size="50" /></td>
					  </tr>
					  <tr>
						<td height="25" bgcolor="#EEEEEE" class="style3"><div align="right">Destaque</div></td>
						<td><select name="destaque" class="form" id="destaque" style="width: 235px;">
							<option value="#">- Selecione uma opção - </option>
							<option value="1">Sim</option>
							<option value="2">Não</option>
						</select></td>
					  </tr>
					  <tr>
						<td> </td>
						<td><input type="submit" name="Submit" value="Atualizar" class="button" />
							<input name="Submit2" type="button" class="button" value="Cancelar" /></td>
					  </tr>
				  </table></td>
				</tr>
				<tr>
				  <td> </td>
				</tr>
			  </table>
									<input type="hidden" name="MM_insert" value="adicionar">
			</form>
			</td>
		  </tr>
		  <tr>
			<td> </td>
		  </tr>
		</table></td>
	  </tr>
	</table></td>
  </tr>
  <tr>
	<td><img src="imagens/curva02.gif" width="700" height="25" /></td>
  </tr>
  <tr>
	<td> </td>
  </tr>
  <tr>
	<td><img src="imagens/rodape.jpg" width="700" height="80" /></td>
  </tr>
</table>
</body>
</html>




Espero ajuda!!

#2 lwirkk

lwirkk

    Veterano

  • Usuários
  • 1314 posts
  • Sexo:Não informado

Posted 22/05/2008, 12:18

Não dá algum error ao enviar a imagem?

E onde está "//Faz upload da imagem"
Teste assim:
move_uploaded_file($FILES[""]["tmp_name"], $imagem_dir);

Posted Image
"Se quiser ser feliz por um dia, vingue-se; se quiser ser feliz por uma vida inteira, perdoe."

Muito Obrigado à todos do fórum, e à toda equipe do fórum! =)




1 user(s) are reading this topic

0 membro(s), 1 visitante(s) e 0 membros anônimo(s)

IPB Skin By Virteq