Foros del Web » Programando para Internet » PHP »

multipart/form-data y formulario junto, es possible ???

Estas en el tema de multipart/form-data y formulario junto, es possible ??? en el foro de PHP en Foros del Web. Tengo un formulario en PHP para insertar un registro en base de datos, lo que quiero ahora es subir un archivo al servidor dejandolo en ...
  #1 (permalink)  
Antiguo 17/06/2008, 10:10
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
multipart/form-data y formulario junto, es possible ???

Tengo un formulario en PHP para insertar un registro en base de datos, lo que quiero ahora es subir un archivo al servidor dejandolo en una carpeta remota.
Mi problema es el siguiente, al subir archivos, utilizo formulario <form enctype="multipart/form-data" ...> y para enviar datos no se utiliza esta accion. Mi problema es que no se como combinarlos y realizar las dos acciones a la vez ¿se puede?
Tengo los dos scripts inserción en BD y subir en dos scripts que funcionan perfectamente, pero por separado ¿como puedo unirlos?.
Gracias...
  #2 (permalink)  
Antiguo 17/06/2008, 10:20
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

puedes colocar el input file dentro de tu formulario... y form enctype="multipart/form-data" lo colocas en donde se abre el form y en el inout file...
saludos
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #3 (permalink)  
Antiguo 17/06/2008, 10:21
Avatar de caricatos
Moderador
 
Fecha de Ingreso: abril-2002
Ubicación: Torremolinos (Málaga)
Mensajes: 19.607
Antigüedad: 22 años
Puntos: 1284
Respuesta: multipart/form-data y formulario junto, es possible ???

Hola:

El enctype y el método post es la combinación... luego la foto la procesas con el array $_FILES (el fichero adjunto lo recuperas desde la url $_FILES["el_name_del_form_o 0"]["tmp_name"]... y el resto de los datos desde el array $_POST (prohibido el método get)... simplemente debes procesar los 2 arrays... prueba leyendo esos datos...

print_r($_FILES);
print_r($_POST);

... verás que te llega todo lo que necesitas...

Saludos
__________________
Por favor:
No hagan preguntas de temas de foros en mensajes privados... no las respondo
  #4 (permalink)  
Antiguo 17/06/2008, 10:22
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

puedes colocar tus codigos??
creo o me parece q estas empezando y no se q tanto entiendas... yo no es q sepa muuucho pero si puedo ayudarte con gusto...
publica tus codigos explicados por fa!
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #5 (permalink)  
Antiguo 17/06/2008, 10:27
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

asi es estoy empezando... muchas gracias
aqui tienes el codigodel formulario:


<form action="subir_archivo_personal-restringido.php" method="POST" enctype="multipart/form-data" name="form1">
<p align="center">
<input name="archivo" type="file" id="archivo" onmouseover="MM_showHideLayers('Layer11','','show' );MM_showHideLayers('Layer11','','show')" value="" size="32" />
<input type="submit" name="Submit" value="Enviar" />
</p>
<p align="center">
<label>nombre
<input type="text" name="textfield" />
</label>
</p>
<p align="center" class="Estilo79">
<label>lujar foto
<input type="text" name="textfield2" />
</label>
</p>
<p align="center" class="Estilo79">
<label>descripcion
<input type="text" name="textfield3" />
</label>
</p>
</form>
  #6 (permalink)  
Antiguo 17/06/2008, 10:31
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

no no no del form... quiero los codigos q usas para el insert de los datos!!!!
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #7 (permalink)  
Antiguo 17/06/2008, 10:34
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

Imagino te refieres a este formulario...
esto es mi pagina "enviar-foto-paso1_personal-restringido.php"

<form method="post" name="form2" action="<?php echo $editFormAction; ?>">
<table align="center">
<tr valign="baseline">
<td nowrap align="right">Nombre:</td>
<td><input type="text" name="nombre" value="" size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Usuario:</td>
<td><input type="text" name="usuario" value="<?php echo $_SESSION['MM_Username']; ?>" size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Lugarfoto:</td>
<td><input type="text" name="lugarfoto" value="" size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">Descripcion:</td>
<td><input type="text" name="descripcion" value="" size="32"></td>
</tr>
<tr valign="baseline">
<td nowrap align="right">&nbsp;</td>
<td><input type="submit" value="Insertar registro"></td>
</tr>
</table>
<input type="hidden" name="foto" value="">
<input type="hidden" name="MM_insert" value="form2">
</form>

despues se dirige a otra pagina donde tengo el multipart/form-data
  #8 (permalink)  
Antiguo 17/06/2008, 10:36
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

mmmmmmmmmmmm malo malo.... donde estan tus sentencias sql???
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #9 (permalink)  
Antiguo 17/06/2008, 10:44
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

esto es lo que necesitas ???
disculpa mi ignirancia:

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$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"] == "form2")) {
$insertSQL = sprintf("INSERT INTO fotos (nombre, usuario, lugarfoto, descripcion, foto) VALUES (%s, %s, %s, %s, %s)",
GetSQLValueString($_POST['nombre'], "text"),
GetSQLValueString($_POST['usuario'], "text"),
GetSQLValueString($_POST['lugarfoto'], "text"),
GetSQLValueString($_POST['descripcion'], "text"),
GetSQLValueString($_POST['foto'], "text"));

mysql_select_db($database_jmisitio, $misitio);
$Result1 = mysql_query($insertSQL, $misitio) or die(mysql_error());

$insertGoTo = "enviar-fotos-paso2_personal_restringido.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
}
?>
  #10 (permalink)  
Antiguo 17/06/2008, 10:46
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

ok y lo q necesitas es q t suba la foto cierto?
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #11 (permalink)  
Antiguo 17/06/2008, 10:47
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

si, asi es
  #12 (permalink)  
Antiguo 17/06/2008, 10:57
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

ok tres cosas

1. Cambia tu consulta asi
Código PHP:
<?php
if (!function_exists("GetSQLValueString")) {
function 
GetSQLValueString($theValue$theType$theDefinedValue ""$theNotDefinedValue ""
{
$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 "'" "''";
break; 
case 
"long":
case 
"int":
$theValue = ($theValue != "") ? intval($theValue) : "''";
break;
case 
"double":
$theValue = ($theValue != "") ? "'" doubleval($theValue) . "'" "''";
break;
case 
"date":
$theValue = ($theValue != "") ? "'" $theValue "'" "''";
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"] == "form2")) {

$ediciondir'fotosdir/';  
$uploaddir=$ediciondir;
if (!
is_dir($ediciondir)) {     mkdir($uploaddir0777);    }
move_uploaded_file($_FILES['foto']['tmp_name'], $uploaddir $_FILES['foto']['name']);    
$filename $_FILES['foto']['name'];

$insertSQL sprintf("INSERT INTO fotos (nombre, usuario, descripcion, foto) VALUES (%s, %s, %s, %s)",
GetSQLValueString($_POST['nombre'], "text"),
GetSQLValueString($_POST['usuario'], "text"),
GetSQLValueString($_POST['descripcion'], "text"),
GetSQLValueString($filename"text"));

mysql_select_db($database_jmisitio$misitio);
$Result1 mysql_query($insertSQL$misitio) or die(mysql_error());

$insertGoTo "enviar-fotos-paso2_personal_restringido.php";
if (isset(
$_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo'?')) ? "&" "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s"$insertGoTo));
}
?>
2. Agrega este java a la pagina donde esta el form para validar extensiones
Código PHP:
<script language="javascript" type="text/javascript">
function 
validar_archivo(archivo) {
    var 
error_archivo;
    
error_archivo=0;
      var 
file=archivo.value;
      
          if (
file=="")
          { 
error_archivo=1; }
          
//texto += "\n\nIngrese Foto"
            
else{
             
                 
// file=document.formulario.FOTO.value
               
extArray = new Array(".gif",".jpg");
               
// Extension de archivos permitidos
               
allowSubmit false;
                 if (!
file) return;

                   while (
file.indexOf("\\") != -1)
                       
file file.slice(file.indexOf("\\") + 1);
                       
ext file.slice(file.indexOf(".")).toLowerCase();
                   
                   for (var 
i=0extArray.lengthi++){
                          if (
extArray[i] == ext){
                             
allowSubmit true;
                             break;
                            }
                    }

                        if (!
allowSubmit) {
                         
error_archivo=2;
                        
// texto += "\n\nFOTO: solo admite archivo con la extensión ''gif, .jpeg , .jpg''";
                         
}
                            }
                            return 
error_archivo;
}



</script> 
3ro. tu form es algo parecido a esto
Código PHP:
<form action="<?php echo $editFormAction?>" method="post" enctype="multipart/form-data" name="form1">
              <table width="414" align="center">
                <tr valign="baseline">
                  <td width="96" align="left" valign="middle" nowrap class="textoFlamukoRojo"><div align="left">Nombre:</div></td>
                  <td width="306" valign="middle" class="textoINDEX"><div align="left">
                      <input name="nombre" type="text" class="textoFlamukoRojo" size="25">
                  </div></td>
                </tr>
                <tr valign="baseline">
                  <td align="left" valign="middle" nowrap class="textoFlamukoRojo"><div align="left">Descripcion</div></td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="descripcion" type="text" class="textoResNot" id="descripcion" size="25">
                      </label></td>
                </tr>
                <tr valign="baseline">
                  <td align="left" valign="middle" nowrap class="textoFlamukoRojo">Usuario</td>
                  <td align="left" valign="middle" class="textoINDEX"><input name="usuario" type="text" class="textoResNot" id="usuario" size="25"></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" class="textoFlamukoRojo"><div align="left">Imagen:</div></td>
                  <td valign="middle" class="textoINDEX"><div align="left">
                      <input name="imagen" type="file" class="textoResNot"  enctype="multipart/form-data">
                  </div></td>
                </tr>
                <tr valign="baseline">
                  <td align="right" valign="middle" class="Estilo6"><div align="left">
                      <input type="hidden" name="MM_insert" value="form1">
                  </div></td>
                  <td valign="middle"><div align="left"></div></td>
                </tr>
                <tr valign="baseline">
                  <td nowrap align="right">&nbsp;</td>
                  <td><div align="left">
                      <input name="submit" type="submit" class="textoTitulos" value="Insertar registro">
                  </div></td>
                </tr>
              </table>
</form>
y una ultima cosita...
elimine el campo lugar foto pues el codigo te la ubica automaticamente

prueba y cuentame
espero t haya ayudado... saludos
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...

Última edición por T4ke0veR; 17/06/2008 a las 11:09
  #13 (permalink)  
Antiguo 17/06/2008, 11:04
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

ok !!! provare...te digo algo...!!
  #14 (permalink)  
Antiguo 17/06/2008, 11:10
Avatar de T4ke0veR  
Fecha de Ingreso: agosto-2007
Ubicación: Quito - Ecuador
Mensajes: 1.720
Antigüedad: 16 años, 8 meses
Puntos: 28
Respuesta: multipart/form-data y formulario junto, es possible ???

por cierto copia otra vez la consulta q la modifique...
otra cosa... recuerda crear en tu base de datos un campo de nombre
id -> tipo INT auto_increment y lo declaras como primario!!!!
__________________
Diseño gráfico, Web, imagen corporativa, publicidad ...
  #15 (permalink)  
Antiguo 18/06/2008, 04:30
 
Fecha de Ingreso: octubre-2007
Mensajes: 724
Antigüedad: 16 años, 6 meses
Puntos: 4
Respuesta: multipart/form-data y formulario junto, es possible ???

He provado , pero no hace nada. provare con otras faplicaciones, ya te informare--... gracias de todas formas...
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 04:17.