Solved

php Insert Record form integration with image upload

Posted on 2013-05-28
4
713 Views
Last Modified: 2013-05-29
Hello
I'm trying to get my record insertion form to include an image upload option

The image uploading hopefully would support an unlimited number of images with a very high size cap, and it would also do the uploading using the same button for the info in text fields.
Any advice on protecting against sql injection would be greatly appreciated
Thanks

Insert Record form (with the upload form in lines 340-349, calls upload_file.php)
 <?php require_once('Connections/heavensk_listings.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($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"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO content (type_of_property, title, content, cep, estado, cidade, barrios_or_distritos, endereco, numero, complemento, internal_ref, useful_area, total_area, parking_space, suite, rooms, address, sales_price_per_sqm, rent_price_per_sqm, condo_price_per_sqm, iptu_per_sqm, sales_price, downpayement, rent_price, condo_price, aceito_permuta, entrada_facilitada, imoveis_com_divida, demais_cond_comerciais, iptu, commission_percent, commission_value, rent_purchase, sales_purchase, sale, rent, name, company_name, company_creci, company_address, phone, phone2, cel, cel2, nextel, personal_creci, email, email2, site1, site2) 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, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['type_of_property'], "text"),
                       GetSQLValueString($_POST['title'], "text"),
                       GetSQLValueString($_POST['content'], "text"),
                       GetSQLValueString($_POST['cep'], "int"),
                       GetSQLValueString($_POST['estado'], "text"),
                       GetSQLValueString($_POST['cidade'], "text"),
                       GetSQLValueString($_POST['barrios_or_distritos'], "text"),
                       GetSQLValueString($_POST['endereco'], "text"),
                       GetSQLValueString($_POST['numero'], "text"),
                       GetSQLValueString($_POST['complemento'], "text"),
                       GetSQLValueString($_POST['internal_ref'], "text"),
                       GetSQLValueString($_POST['useful_area'], "int"),
                       GetSQLValueString($_POST['total_area'], "text"),
                       GetSQLValueString($_POST['parking_space'], "text"),
                       GetSQLValueString($_POST['suite'], "text"),
                       GetSQLValueString($_POST['rooms'], "int"),
                       GetSQLValueString($_POST['sales_price_per_sqm'], "text"),
                       GetSQLValueString($_POST['rent_price_per_sqm'], "text"),
                       GetSQLValueString($_POST['condo_price_per_sqm'], "text"),
                       GetSQLValueString($_POST['iptu_per_sqm'], "text"),
                       GetSQLValueString($_POST['sales_price'], "int"),
                       GetSQLValueString($_POST['downpayement'], "text"),
                       GetSQLValueString($_POST['rent_price'], "text"),
                       GetSQLValueString($_POST['condo_price'], "text"),
                       GetSQLValueString(isset($_POST['aceito_permuta']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString(isset($_POST['entrada_facilitada']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString(isset($_POST['imoveis_com_divida']) ? "true" : "", "defined","'Y'","'N'"),
                       GetSQLValueString($_POST['demais_cond_comerciais'], "text"),
                       GetSQLValueString($_POST['iptu'], "text"),
                       GetSQLValueString($_POST['commission_percent'], "text"), 
                       GetSQLValueString($_POST['rent_purchase'], "text"),
                       GetSQLValueString($_POST['sales_purchase'], "text"),
                       GetSQLValueString($_POST['sale'], "text"),
                       GetSQLValueString($_POST['rent'], "text"),
                       GetSQLValueString($_POST['name'], "text"),
                       GetSQLValueString($_POST['company_name'], "text"),
                       GetSQLValueString($_POST['company_creci'], "text"),
                       GetSQLValueString($_POST['company_address'], "text"),
                       GetSQLValueString($_POST['phone'], "int"),
                       GetSQLValueString($_POST['phone2'], "int"),
                       GetSQLValueString($_POST['cel'], "int"),
                       GetSQLValueString($_POST['cel2'], "int"),
                       GetSQLValueString($_POST['nextel'], "text"),
                       GetSQLValueString($_POST['personal_creci'], "text"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['email2'], "text"),
                       GetSQLValueString($_POST['site1'], "text"),
                       GetSQLValueString($_POST['site2'], "text"));

  mysql_select_db($database_heavensk_listings, $heavensk_listings);
  $Result1 = mysql_query($insertSQL, $heavensk_listings) or die(mysql_error());

  $insertGoTo = "image.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>
<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Adicionar um Anúncio</title>
<script src="SpryAssets/SpryValidationSelect.js" type="text/javascript"></script>
<script src="SpryAssets/SpryValidationTextField.js" type="text/javascript"></script>
<link href="SpryAssets/SpryValidationSelect.css" rel="stylesheet" type="text/css" />
<link href="SpryAssets/SpryValidationTextField.css" rel="stylesheet" type="text/css" />
<style type="text/css">
body {
	background-image: url(wp-content/uploads/2013/05/content_insert.png);
	background-repeat: repeat-x;
}
</style>
</head>
<body>
<form action="<?php echo $editFormAction; ?>" method="post" name="form2" id="form2">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.midiata.com.br/cliente_arede/"><img src="wp-content/uploads/2013/05/logo-11-150x150.png" width="150" height="150" /></a>

<table align="center"><td align="center"><h1 style="color:#FFF"">Adicionar um Imovel</h1></p></td>
</table>
  <table align="center" style="color:#FFF">
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Tipo de Imóvel:</td>
      <td><select name="type_of_property">
        <option value="apartamento" <?php if (!(strcmp("apartamento", ""))) {echo "SELECTED";} ?>>Apartamento</option>
        <option value="Kitchenette_ou_Conjugados" <?php if (!(strcmp("Kitchenette_ou_Conjugados", ""))) {echo "SELECTED";} ?>>Kitchenette/Conjugados</option>
        <option value="casa_padrao" <?php if (!(strcmp("casa_padrao", ""))) {echo "SELECTED";} ?>>Casa Padrão</option>
        <option value="terreno_padrao" <?php if (!(strcmp("terreno_padrao", ""))) {echo "SELECTED";} ?>>Terreno Padrão</option>
        <option value="box_ou_garagem" <?php if (!(strcmp("box_ou_garagem", ""))) {echo "SELECTED";} ?>>Box/Garagem</option>
        <option value="casa_comercial" <?php if (!(strcmp("casa_comercial", ""))) {echo "SELECTED";} ?>>Casa Comercial</option>
        <option value="casa_de_condominio" <?php if (!(strcmp("casa_de_condominio", ""))) {echo "SELECTED";} ?>>Casa de Condomínio</option>
        <option value="casa_de_vila" <?php if (!(strcmp("casa_de_vila", ""))) {echo "SELECTED";} ?>>Casa de Vila</option>
        <option value="chacara" <?php if (!(strcmp("chacara", ""))) {echo "SELECTED";} ?>>Chacara</option>
        <option value="conjunto_comercial_ou_sala" <?php if (!(strcmp("conjunto_comercial_ou_sala", ""))) {echo "SELECTED";} ?>>Conjunto Comercial/Sala</option>
        <option value="fazenda" <?php if (!(strcmp("fazenda", ""))) {echo "SELECTED";} ?>>Fazenda</option>
        <option value="flat" <?php if (!(strcmp("flat", ""))) {echo "SELECTED";} ?>>Flat</option>
        <option value="galpao_ou_deposito_ou_aramzen" <?php if (!(strcmp("galpao_ou_deposito_ou_aramzen", ""))) {echo "SELECTED";} ?>>Galpão/Deposito/Armazen</option>
        <option value="haras" <?php if (!(strcmp("haras", ""))) {echo "SELECTED";} ?>>Haras</option>
        <option value="hotel" <?php if (!(strcmp("hotel", ""))) {echo "SELECTED";} ?>>Hotel</option>
        <option value="industria" <?php if (!(strcmp("industria", ""))) {echo "SELECTED";} ?>>Industria</option>
        <option value="loja_shopping_ou_ct_comercial" <?php if (!(strcmp("loja_shopping_ou_ct_comercial", ""))) {echo "SELECTED";} ?>>Loja Shopping/CT Comercial</option>
        <option value="loja_ou_salao" <?php if (!(strcmp("loja_ou_salao", ""))) {echo "SELECTED";} ?>>Loja/Salao</option>
        <option value="loteamento_ou_condominio" <?php if (!(strcmp("loteamento_ou_condominio", ""))) {echo "SELECTED";} ?>>Loteamento/Condominio</option>
        <option value="motel" <?php if (!(strcmp("motel", ""))) {echo "SELECTED";} ?>>Motel</option>
        <option value="pousada_ou_chale" <?php if (!(strcmp("pousada_ou_chale", ""))) {echo "SELECTED";} ?>>Pousada/Chale</option>
        <option value="predio_inteiro" <?php if (!(strcmp("predio_inteiro", ""))) {echo "SELECTED";} ?>>Predio Inteiro</option>
        <option value="sitio" <?php if (!(strcmp("sitio", ""))) {echo "SELECTED";} ?>>Sitio</option>
        <option value="studio" <?php if (!(strcmp("studio", ""))) {echo "SELECTED";} ?>>Studio</option>
      </select></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Título:</td>
      <td><span id="sprytextfield1">
        <input type="text" name="title" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Descrição:</td>
      <td><span id="sprytextfield2">
        <input type="text" name="content" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">CEP:</td>
      <td><span id="sprytextfield3">
        <input type="text" name="cep" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Estado(UF):</td>
      <td><span id="sprytextfield4">
        <input type="text" name="estado" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Cidade:</td>
      <td><span id="sprytextfield5">
        <input type="text" name="cidade" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Bairros/Distritos:</td>
      <td><span id="sprytextfield6">
        <input type="text" name="barrios_or_distritos" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Endereço:</td>
      <td><span id="sprytextfield7">
        <input type="text" name="endereco" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Número:</td>
      <td><span id="sprytextfield10">
        <input type="text" name="numero" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Complemento:</td>
      <td><span id="sprytextfield11">
        <input type="text" name="complemento" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Referência Interna:</td>
      <td><span id="sprytextfield12">
        <input type="text" name="internal_ref" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Área útil (m²):</td>
      <td><span id="sprytextfield8">
        <input type="text" name="useful_area" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Área Total (m²):</td>
      <td><span id="sprytextfield13">
        <input type="text" name="total_area" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Vagas de Garagem:</td>
      <td><span id="sprytextfield14">
        <input type="text" name="parking_space" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Suítes:</td>
      <td><span id="sprytextfield15">
        <input type="text" name="suite" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Quartos/Dormitórios:</td>
      <td><span id="sprytextfield16">
        <input type="text" name="rooms" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Preço do venda (m²):</td>
      <td><span id="sprytextfield17">
        <input type="text" name="sales_price_per_sqm" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Preço do renda (m²):</td>
      <td><span id="sprytextfield18">
        <input type="text" name="rent_price_per_sqm" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Preço do Condomínio (m²) : </td>
      <td><span id="sprytextfield19">
        <input type="text" name="condo_price_per_sqm" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Iptu (m²):</td>
      <td><span id="sprytextfield20">
        <input type="text" name="iptu_per_sqm" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Valor Total de Venda (R$):</td>
      <td><span id="sprytextfield9">
        <input type="text" name="sales_price" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Valor de Entrada (R$):</td>
      <td><span id="sprytextfield21">
        <input type="text" name="downpayement" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Preço da Alugel:</td>
      <td><span id="sprytextfield22">
        <input type="text" name="rent_price" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Preço do Condomínio:</td>
      <td><span id="sprytextfield23">
        <input type="text" name="condo_price" value="" size="32" />
      <span class="textfieldRequiredMsg">A value is required.</span></span></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Condições Comerciais:</td>
      <td>Aceito permuta        <input type="checkbox" name="aceito_permuta" value="" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"></td>
      <td>Entrada facilitada        <input type="checkbox" name="entrada_facilitada" value="" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"></td>
      <td>Imoveis com divida        <input type="checkbox" name="imoveis_com_divida" value="" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Comissão</td>
      <td valign="baseline"><table>
        <tr>
          <td><input type="radio" name="commission" value="value" />
            Valor</td>
        </tr>
        <tr>
          <td><input type="radio" name="commission" value="porcentagem" />
            Porcentagem</td>
        </tr>
      </table></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right" valign="top">Demais cond. Comerciais:</td>
      <td><textarea name="demais_cond_comerciais" cols="50" rows="5"></textarea></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Iptu:</td>
      <td><input type="text" name="iptu" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Rent purchase:</td>
      <td><input type="text" name="rent_purchase" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Vendas Comprar:</td>
      <td><input type="text" name="sales_purchase" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Venda:</td>
      <td><input type="checkbox" name="sale" value="" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Alugar:</td>
      <td><input type="checkbox" name="rent" value="" /></td>
    </tr>
    
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Fazer upload de até 20 imagens</td>
      <td><form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file"></label>
<input type="file" name="file" id="file" /> 
<input type="submit" name="submit" value="Submit" />
</form></td></tr>
    
   </table>
   
   <table align="center" style="color:#FFF"><td align="center"><h3 style="text-decoration:underline">Dados de Corretor</h3></p></td>
</table>
   
<table align="center" style="color:#FFF">
        
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nome:</td>
      <td><input type="text" name="name" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nome da Empresa:</td>
      <td><input type="text" name="company_name" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right"> Creci da Empresa:</td>
      <td><input type="text" name="company_creci" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Endereço da Empresa:</td>
      <td><input type="text" name="company_address" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Telefone:</td>
      <td><input type="text" name="phone" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Telefone Secundário:</td>
      <td><input type="text" name="phone2" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Celular:</td>
      <td><input type="text" name="cel" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Celular Secundário:</td>
      <td><input type="text" name="cel2" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Nextel:</td>
      <td><input type="text" name="nextel" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Creci Pessoal:</td>
      <td><input type="text" name="personal_creci" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Email:</td>
      <td><input type="text" name="email" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Email Secundário:</td>
      <td><input type="text" name="email2" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Site:</td>
      <td><input type="text" name="site1" value="" size="32" /></td>
    </tr>
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">Site Secundário:</td>
      <td><input type="text" name="site2" value="" size="32" /></td>   </tr>     
    <tr valign="baseline">
      <td nowrap="nowrap" align="right">&nbsp;</td>
      <td><input type="submit" value="" style=" background:url(wp-content/uploads/2013/05/content_insert_add.png) no-repeat; width:330px; height:49px; padding:0px 0 4px 0; border:none; text-indent: -1000em; cursor:pointer;"/></td>
      <td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form2" />
</form>



<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<script type="text/javascript">
var spryselect1 = new Spry.Widget.ValidationSelect("spryselect1");
var sprytextfield1 = new Spry.Widget.ValidationTextField("sprytextfield1");
var sprytextfield2 = new Spry.Widget.ValidationTextField("sprytextfield2");
var sprytextfield3 = new Spry.Widget.ValidationTextField("sprytextfield3");
var sprytextfield4 = new Spry.Widget.ValidationTextField("sprytextfield4");
var sprytextfield5 = new Spry.Widget.ValidationTextField("sprytextfield5");
var sprytextfield6 = new Spry.Widget.ValidationTextField("sprytextfield6");
var sprytextfield7 = new Spry.Widget.ValidationTextField("sprytextfield7");
var sprytextfield8 = new Spry.Widget.ValidationTextField("sprytextfield8");
var sprytextfield9 = new Spry.Widget.ValidationTextField("sprytextfield9");
var sprytextfield10 = new Spry.Widget.ValidationTextField("sprytextfield10");
var sprytextfield11 = new Spry.Widget.ValidationTextField("sprytextfield11");
var sprytextfield12 = new Spry.Widget.ValidationTextField("sprytextfield12");
var sprytextfield13 = new Spry.Widget.ValidationTextField("sprytextfield13");
var sprytextfield14 = new Spry.Widget.ValidationTextField("sprytextfield14");
var sprytextfield15 = new Spry.Widget.ValidationTextField("sprytextfield15");
var sprytextfield16 = new Spry.Widget.ValidationTextField("sprytextfield16");
var sprytextfield17 = new Spry.Widget.ValidationTextField("sprytextfield17");
var sprytextfield18 = new Spry.Widget.ValidationTextField("sprytextfield18");
var sprytextfield19 = new Spry.Widget.ValidationTextField("sprytextfield19");
var sprytextfield20 = new Spry.Widget.ValidationTextField("sprytextfield20");
var sprytextfield21 = new Spry.Widget.ValidationTextField("sprytextfield21");
var sprytextfield22 = new Spry.Widget.ValidationTextField("sprytextfield22");
var sprytextfield23 = new Spry.Widget.ValidationTextField("sprytextfield23");
</script>

<p><strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;© 2012 Copyright by Midiata.</strong> All rights reserved.|<strong> © 2012 Direitos Autorais por Midiata.</strong> Todos os direitos reservados.</p>


</body>
</html>

Open in new window


upload_file.php
(php code that is being called by the form above)
<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))

&& ($_FILES["file"]["size"] < 20000000000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("images/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "images/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "images/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

Open in new window

0
Comment
Question by:Gmpcs
  • 3
4 Comments
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 39202998
You might want to step away from the Dreamweaver stuff and get a real foundation in how PHP works.  This book is a good start.
http://www.amazon.com/PHP-MySQL-Web-Development-Edition/dp/0672329166/

With hundreds of lines of code in your examples here, it may not be possible for me to tease out the essential moving parts.  But I can show you a teaching example of how to upload a file (or three).  This works for me.

<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php
// http://php.net/manual/en/reserved.variables.files.php

// MANUAL PAGES THAT ARE IMPORTANT IF YOU ARE DEALING WITH LARGE FILES
// http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
// http://php.net/manual/en/ini.core.php#ini.post-max-size
// http://php.net/manual/en/info.configuration.php#ini.max-input-time


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME URL
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a target=\"_blank\" href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

Hope that helps some, ~Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39203093
What was wrong with the answer?  Please see the grading guidelines:
http://www.experts-exchange.com/help/viewHelpPage.jsp?helpPageID=26

If you are not completely comfortable with the answer and cannot give a grade of "A" (the default and expected grade) you might want to make a post back explaining what is missing!

RSVP, thanks.  ~Ray
0
 

Author Comment

by:Gmpcs
ID: 39205187
Hello Ray, I already had an upload files script. The essence of my question dwelled on integrating it with my current form .
A B grade means the solution given lacked some information or required you to do a good amount of extra work to resolve the problem.
Your answer is appreciated.
Thanks Ray
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 39205767
Like I said, "... you might want to make a post back explaining what is missing!"  This would be something you would want to do before closing the question with a bad grade.  We are only experts, not mind readers, and if our answers are not well-targeted you can expect additional help once you engage in dialog.

Buy that book! ~Ray
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now