Foros del Web » Programando para Internet » PHP »

subir archivo en mi formulario.

Estas en el tema de subir archivo en mi formulario. en el foro de PHP en Foros del Web. Buenas noches amigos , nuevamente vengo por aca a pedir de su enorme ayuda estoy realizando un formulario el cual envia como campos. Titulo descripcion ...
  #1 (permalink)  
Antiguo 16/06/2013, 20:56
Avatar de nexus44  
Fecha de Ingreso: octubre-2012
Ubicación: Piura
Mensajes: 108
Antigüedad: 11 años, 5 meses
Puntos: 1
Información subir archivo en mi formulario.

Buenas noches amigos , nuevamente vengo por aca a pedir de su enorme ayuda estoy realizando un formulario el cual envia como campos.

Titulo
descripcion
fichero
grupo:
admin
user
premium

Entonces el problema que tengo es que al momento que quiero subir un archivo , no lo esta subiendo ; mejor dicho almacenandolo en mi espacio del servidor , al almacenarlo tendra la opcion de descargar al grupo que se le asigno el fichero con los demas datos mencionados.

Indagando encontre un codigo que quisiera saber como asignarlo en el campo fichero y asi lo pueda almacenar estado haciendolo , utilizando la funcion action y llamando al php pero no me sube el archivo no se como podrian ayudarme en este caso. GRACIAS

nueva_noticia.php


Código PHP:
Ver original
  1. <?php require_once('Connections/con_usuarios.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   if (PHP_VERSION < 6) {
  7.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  8.   }
  9.  
  10.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  11.  
  12.   switch ($theType) {
  13.     case "text":
  14.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  15.       break;    
  16.     case "long":
  17.     case "int":
  18.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  19.       break;
  20.     case "double":
  21.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  22.       break;
  23.     case "date":
  24.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  25.       break;
  26.     case "defined":
  27.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  28.       break;
  29.   }
  30.   return $theValue;
  31. }
  32. }
  33.  
  34. $editFormAction = $_SERVER['PHP_SELF'];
  35. if (isset($_SERVER['QUERY_STRING'])) {
  36.   $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
  37. }
  38.  
  39. if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  40.   $insertSQL = sprintf("INSERT INTO noticias (titular, texto, fichero, grupo) VALUES (%s, %s, %s, %s)",
  41.                        GetSQLValueString($_POST['titular'], "text"),
  42.                        GetSQLValueString($_POST['texto'], "text"),
  43.                        GetSQLValueString($_POST['fichero'] , "text"),
  44.                        GetSQLValueString($_POST['grupo'], "int"));
  45.  
  46.   mysql_select_db($database_con_usuarios, $con_usuarios);
  47.   $Result1 = mysql_query($insertSQL, $con_usuarios) or die(mysql_error());
  48.  
  49.   $insertGoTo = "acceso.php";
  50.   if (isset($_SERVER['QUERY_STRING'])) {
  51.     $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
  52.     $insertGoTo .= $_SERVER['QUERY_STRING'];
  53.   }
  54.   header(sprintf("Location: %s", $insertGoTo));
  55. }
  56. ?>
  57. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  58. <html xmlns="http://www.w3.org/1999/xhtml"><!-- InstanceBegin template="/Templates/base.dwt.php" codeOutsideHTMLIsLocked="false" -->
  59. <head>
  60. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  61. <!-- InstanceBeginEditable name="doctitle" -->
  62. <title>.::Nueva noticia::.</title>
  63. <!-- InstanceEndEditable -->
  64. <style type="text/css">
  65. <!--
  66. body {
  67.     margin-top: 0px;
  68.     background-image: url(fondo.jpg);
  69.     background-repeat: repeat-x;
  70. }
  71. -->
  72. </style>
  73. <!-- InstanceBeginEditable name="head" -->
  74. <script type="text/javascript">
  75. <!--
  76. function MM_validateForm() { //v4.0
  77.   if (document.getElementById){
  78.     var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
  79.     for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
  80.       if (val) { nm=val.name; if ((val=val.value)!="") {
  81.         if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
  82.           if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
  83.         } else if (test!='R') { num = parseFloat(val);
  84.           if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
  85.           if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
  86.             min=test.substring(8,p); max=test.substring(p+1);
  87.             if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
  88.       } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
  89.     } if (errors) alert('The following error(s) occurred:\n'+errors);
  90.     document.MM_returnValue = (errors == '');
  91. } }
  92. //-->
  93. </script>
  94. <!-- InstanceEndEditable -->
  95. </head>
  96.  
  97. <body>
  98. <table width="80%" border="0" align="center">
  99.  
  100.   <tr>
  101.     <td align="center" bgcolor="#129ae8"><!-- InstanceBeginEditable name="contenido" -->
  102.       <p>&nbsp;</p>
  103.       <p><img src="imagenes/new.jpg" width="500" height="100" /></p>
  104.       <form action="<?php echo $editFormAction; ?>" method="post" name="form1" id="form1">
  105.         <table align="center" onfocus="MM_validateForm('titular','','R','texto','','R');return document.MM_returnValue">
  106.           <tr valign="baseline">
  107.             <td nowrap="nowrap" align="right">Titular:</td>
  108.             <td align="left"><input name="titular" type="text" id="titular" value="" size="32" /></td>
  109.           </tr>
  110.           <tr valign="baseline">
  111.             <td nowrap="nowrap" align="right" valign="top">Texto:</td>
  112.             <td align="left"><textarea name="texto" cols="50" rows="5" id="texto"></textarea></td>
  113.           </tr>
  114.           <tr valign="baseline">
  115.             <td nowrap="nowrap" align="right" valign="top">Fichero</td>
  116.             <td align="left"><input type="file" name="fichero" id="fichero" value="<?php
  117.  
  118. //Definimos el destino de nuestro archivo a subir
  119. $target = "/public_html/elvis/descargas/";
  120.  
  121. //Concatenamos el nombre del archivo a nuestro directorio
  122. $target = $target . basename( $_FILES['fichero']['name']) ;
  123.  
  124. //Movemos el archivo subido al directorio que definimos
  125. if(move_uploaded_file($_FILES['fichero']['tmp_name'], $target))
  126. {
  127. echo "El archivo ". basename( $_FILES['fichero']['name']). " ha sido subido";
  128. }
  129. else {
  130. echo "Lo sentimos, hubo un problema subiendo tu archivo";
  131. }
  132. ?>" />
  133.               </td>
  134.           </tr>
  135.           <tr valign="baseline">
  136.             <td align="right" valign="top" nowrap="nowrap">Grupo:</td>
  137.             <td align="left" valign="baseline"><table>
  138.               <tr>
  139.                 <td><input type="radio" name="grupo" value="1" />
  140.                   Todos</td>
  141.               </tr>
  142.               <tr>
  143.                 <td><input type="radio" name="grupo" value="2" />
  144.                   Usuarios</td>
  145.               </tr>
  146.               <tr>
  147.                 <td><input type="radio" name="grupo" value="3" />                  Premium</td>
  148.               </tr>
  149.             </table></td>
  150.           </tr>
  151.           <tr valign="baseline">
  152.             <td nowrap="nowrap" align="right">&nbsp;</td>
  153.             <td align="left"><input type="submit" onclick="MM_validateForm('titular','','R','texto','','R');return document.MM_returnValue" value="Insertar noticia" /></td>
  154.           </tr>
  155.         </table>
  156.         <input type="hidden" name="MM_insert" value="form1" />
  157.       </form>
  158.      
  159.       <p>&nbsp;</p>
  160.       <td><a href="acceso.php"><img src="imagenes/panl.jpg"/></a></td>
  161.     <!-- InstanceEndEditable --></td>
  162.   </tr>
  163. </table>
  164. </body>
  165. <!-- InstanceEnd --></html>


subir.php


Código PHP:
Ver original
  1. <?php
  2.  
  3. //Definimos el destino de nuestro archivo a subir
  4. $target = "/public_html/elvis/descargas/";
  5.  
  6. //Concatenamos el nombre del archivo a nuestro directorio
  7. $target = $target . basename( $_FILES['fichero']['name']) ;
  8.  
  9. //Movemos el archivo subido al directorio que definimos
  10. if(move_uploaded_file($_FILES['fichero']['tmp_name'], $target))
  11. {
  12. echo "El archivo ". basename( $_FILES['fichero']['name']). " ha sido subido";
  13. }
  14. else {
  15. echo "Lo sentimos, hubo un problema subiendo tu archivo";
  16. }
  17. ?>
__________________

"Nuestra capacidad se aleja de la Humanidad"

Última edición por nexus44; 16/06/2013 a las 20:58 Razón: php
  #2 (permalink)  
Antiguo 17/06/2013, 01:40
 
Fecha de Ingreso: marzo-2008
Mensajes: 69
Antigüedad: 16 años, 1 mes
Puntos: 9
Respuesta: subir archivo en mi formulario.

Así sin mirar mucho el código tu formulario no esta bien definido para subir ficheros:

<form action="upload_file.php" method="post" enctype="multipart/form-data">
  #3 (permalink)  
Antiguo 17/06/2013, 10:21
Avatar de Italico76  
Fecha de Ingreso: abril-2007
Mensajes: 3.303
Antigüedad: 17 años
Puntos: 292
Respuesta: subir archivo en mi formulario.

Estas colocando el INPUT FILE y a continuacion ya lo quieres procesar..... deberias ordenar un poco tu codigo y separar el formulario (vista) de la logica o procesamiento de ese formulario
__________________
Salu2!
  #4 (permalink)  
Antiguo 17/06/2013, 22:54
Avatar de nexus44  
Fecha de Ingreso: octubre-2012
Ubicación: Piura
Mensajes: 108
Antigüedad: 11 años, 5 meses
Puntos: 1
Respuesta: subir archivo en mi formulario.

Respondiendo :

Para ser mas especifico este es el codigo que encontre investigando no lo hice yo; por lo tanto lo he asigando de la misma manera ami formulario pero no me da aqui dejo el codigo , espero su grata ayuda , ltalico76 disculpa mi ignorancia pero aprendo poco a poco gustozamente hago peticion a tu ayuda tanto ala tuya amigo txandy.

Lo que he logrado hasta el momento es que me almacene en mi bd tan solo el nombre del fichero ejemplo . web.rar pero no me lo esta almacenando en mi ruta expuesta donde debe guardarce y luego descargarla.

Por lo tanto quisiera hacer la consulta , en mi base de datos el tipo de dato "fichero" vendria a ser varchar? .


upload.php

Código PHP:
Ver original
  1. <?php
  2.  
  3. //Definimos el destino de nuestro archivo a subir
  4. //esta es mi RUTA DONDE DEBE GUARDARSE EL ARCHIVO SUBIDO SUPUESTAMENTE PERO NO LO ALMACENA HAY.
  5. $target = "./descargas/";
  6.  
  7. //Concatenamos el nombre del archivo a nuestro directorio
  8. $target = $target . basename( $_FILES['uploaded']['name']) ;
  9.  
  10. //Movemos el archivo subido al directorio que definimos
  11. if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))
  12. {
  13. echo "El archivo ". basename( $_FILES['uploaded']['name']). " ha sido subido";
  14. }
  15. else {
  16. echo "Lo sentimos, hubo un problema subiendo tu archivo";
  17. }
  18. ?>


index.html
Código HTML:
Ver original
  1. <form action="upload.php" enctype="multipart/form-data" method="POST">
  2. Por favor, escoge un archivo: <input name="uploaded" type="file" />
  3.  
  4. <input type="submit" value="Upload" />
  5.  
  6. </form>

GRACIAS
__________________

"Nuestra capacidad se aleja de la Humanidad"

Etiquetas: formulario, html, mysql, select, sql, usuarios
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 17:45.