Foros del Web » Programando para Internet » PHP »

Seleccionar múltiples archivos de una vez.

Estas en el tema de Seleccionar múltiples archivos de una vez. en el foro de PHP en Foros del Web. Bueno, primero que nada buenos días, les vengo a presentar mi duda, quisiera saber como hacer para seleccionar múltiples archivos mediante un formulario, yo tengo ...
  #1 (permalink)  
Antiguo 12/02/2012, 09:03
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Seleccionar múltiples archivos de una vez.

Bueno, primero que nada buenos días, les vengo a presentar mi duda, quisiera saber como hacer para seleccionar múltiples archivos mediante un formulario, yo tengo un hosting de imágenes, y es muy incómodo subir imagen por imagen, asi que decidí ver que puedo hacer para llevar a cabo esto... Si alguien me diera una mano se lo agradecería. También soy medio novato en PHP, asi que si me dieran una mano mejor, dejo mis archivos:

formulario:
Código HTML:
Ver original
  1. <form method=\"GET\" action='search.php'>
  2.   <table width=900 bgcolor='#528A89' style=\"BORDER: #b1ddf6 2px solid;\">
  3.  <tr height=40>
  4.    <td align=left width=400>&nbsp; &nbsp;<span class="Estilo3">Buscar
  5.    <LABEL id='message'>:</LABEL>
  6.    </span>
  7.    <LABEL id='message'> </LABEL>
  8.    &nbsp;<input type='text' name='query' size=30 maxlength='100'>
  9.    &nbsp; &nbsp; <input type='submit' value='Buscar'> </td>
  10.   <td>
  11.     <LABEL id='title'><span class="Estilo3">Buscar por :</span> </LABEL>
  12.     &nbsp; &nbsp;
  13.     <input type='radio' name='opt' value='tags' CHECKED> &nbsp; <span class="Estilo3">Tags
  14.     <input type='radio' name='opt' value='gallery'>
  15. &nbsp; Galer&iacute;a </span></td>
  16.   <td>
  17.     <div align="center"><a href="search.php" class="Estilo5">Buscador Avanzado</a> </div></td>
  18. </tr></table>
  19. </form>

Sigo abajo porque no entra.
__________________
WWW.LLORK.COM - El futuro es nuestro
Blog de descargas, tutoriales, guías, noticias y más.
  #2 (permalink)  
Antiguo 12/02/2012, 09:03
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Seleccionar múltiples archivos de una vez.

process.php
Código PHP:
Ver original
  1. <?php
  2.   $session = false;
  3.    include("db-info.php");
  4.   $link = mysql_connect($server, $user, $pass);
  5.   if(!mysql_select_db($database)) die(mysql_error());
  6.     include("loadsettings.inc.php");
  7.   $type = "public";
  8.    if (isset($_SESSION["imagehost-user"]))
  9.    {
  10.       $session = true;
  11.       $username = $_SESSION["imagehost-user"];
  12.       $password = $_SESSION["imagehost-pass"];
  13.        $q = "SELECT id FROM `members` WHERE (username = '$username') and (password = '$password')";
  14.       if(!($result_set = mysql_query($q))) die(mysql_error());
  15.       $number = mysql_num_rows($result_set);
  16.      
  17.       if (!$number) {
  18.          session_destroy();
  19.          $session = false;
  20.       }else {
  21.          $row = mysql_fetch_row($result_set);
  22.          $loggedId = $row[0];
  23.          
  24.          if (isset($_POST["tags1"])) {
  25.  
  26.             $opt = $_POST['opt'];
  27.             if ($opt == "gallery") {
  28.                $galleryid = $_POST["galleryid"];
  29.                $result = mysql_query("SELECT type FROM `galleries` WHERE id = '$galleryid'");
  30.                $n = mysql_num_rows($result);
  31.                if (!$n) die();
  32.                $row = mysql_fetch_array($result);
  33.                $type = $row['type'];
  34.             }
  35.             else {
  36.                if (isset($_POST["private"]))
  37.                   $type = "private";
  38.                else
  39.                   $type = "public";
  40.             }
  41.          }
  42.       }
  43.     }
  44.    else
  45.       $session = false;
  46. ?>
  47.  
  48. <html>
  49. <head>
  50. <title><? echo $webtitle; ?> -  Hosting de Imagenes</title>
  51. <link rel="stylesheet" href="style.css" type="text/css" />
  52. </head>
  53. <body link=#336699 vlink=#336699 alink=#336699>
  54. <?php include("header.php"); ?>
  55.  
  56. <center>
  57. <div class="content-container">
  58.  
  59.   <p>
  60.    <?php
  61.  
  62. function findExtension ($filename)
  63. {
  64.    $filename = strtolower($filename) ;
  65.    $exts = split("[/\\.]", $filename) ;
  66.    $n = count($exts)-1;
  67.    $exts = $exts[$n];
  68.    return $exts;
  69. }
  70.  
  71. function imagecreatefromunknown($path) {
  72.  
  73.    $ext = findExtension($path);
  74.    
  75.    switch ($ext) {
  76.       case "jpg":
  77.         $img = imagecreatefromjpeg($path);
  78.         break;
  79.       case "gif":
  80.         $img = imagecreatefromgif($path);
  81.         break;
  82.       case "png":
  83.         $img = imagecreatefrompng($path);
  84.         break;
  85.   }
  86.  
  87.   return $img;
  88. }
  89.  
  90. $max = 5;
  91. $total = 0;
  92.  
  93.  
  94. if (isset($_POST["tags1"])) {
  95.  
  96.    $date = date("d-m-y");
  97.    $lastaccess = date("y-m-d");
  98.    $ip= $_SERVER['REMOTE_ADDR'];
  99.  
  100.    //CHECK IF THE IP OF THE PERSON IS BLOCKED OR NOT
  101.    $result = mysql_query("SELECT id FROM `blockedip` WHERE ip = '$ip'");
  102.    $number = mysql_num_rows($result);
  103.    if ($number) die("Lo sentimos! Su IP fue blockeada para subir imagenes. <br><br><a href='index.php'>Volver al Inicio</a>");
  104.  
  105.    for ($i=1; $i < ($max+1); $i++)
  106.    {  
  107.       if (trim($_FILES["image" . $i]["name"]) != "")  {
  108.            
  109.            $total = $total + 1;
  110.            if ( (trim($_POST["tags" . $i]) != "") ) {
  111.          
  112.                 $tags = htmlspecialchars(trim($_POST["tags" . $i]));
  113.                
  114.                 $name = "image" . $i;
  115.  
  116.                 //CHECK IF VALID IMAGE TYPE
  117.                 if (( ($_FILES[$name]["type"] == "image/gif")
  118.                    || ($_FILES[$name]["type"] == "image/jpeg")
  119.                    || ($_FILES[$name]["type"] == "image/pjpeg")
  120.                    || ($_FILES[$name]["type"] == "image/x-png")
  121.                    || ($_FILES[$name]["type"] == "image/bmp")
  122.                    || ($_FILES[$name]["type"] == "image/png")))
  123.                 {
  124.  
  125.                 $size = intval(($_FILES[$name]["size"] / 1024) / 1024);
  126.                  
  127.                  if ($session == true)
  128.                     $limit = $maxsizemember;
  129.                  else
  130.                     $limit = $maxsizeguest;  
  131.  
  132.                    if ($size > $limit)
  133.                        die ("Lo sentimos! El tamañno de la imagen exede los $limit Mb.");
  134.  
  135.  
  136.                    if ($_FILES[$name]["error"] > 0)  {
  137.                        die("Error: " . $_FILES[$name]["error"]);
  138.                    }
  139.                    else {
  140.                        $n = $_FILES[$name]["name"];
  141.                        $rndName = md5($n . date("d-m-y") . time()) . "." . findExtension($n);
  142.                        $uploadPath = "pictures/" . $rndName;
  143.                        $tempPath = $_FILES[$name]["tmp_name"];
  144.                        move_uploaded_file($tempPath, $uploadPath);
  145.                    }
  146.  
  147.                 }
  148.                 else
  149.                    die("Lo sentimos!! \"{$_FILES[$name]["name"]}\" Es una imagen inv&aacute;lida.");
  150.  
  151.                 $imagePath = $uploadPath;
  152.      
  153.                 $img = imagecreatefromunknown($imagePath);
  154.                                  
  155.                 $mainWidth = imagesx($img);
  156.                 $mainHeight = imagesy($img);
  157.              
  158.                 if (($mainWidth > 0) && ($mainWidth < 10000) && ($mainHeight < 10000))
  159.                 {
  160.                      
  161.                  $a = ($mainWidth >= $mainHeight) ? $mainWidth : $mainHeight;
  162.    
  163.                  $div = $a / 150;
  164.                  $thumbWidth = intval($mainWidth / $div);
  165.                  $thumbHeight = intval($mainHeight / $div);
  166.  
  167.                  $myThumb = imagecreatetruecolor($thumbWidth, $thumbHeight);
  168.                  imagecopyresampled($myThumb, $img, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainWidth, $mainHeight);
  169.                  $thumbPath = "thumbnails/" . basename($imagePath);
  170.                  imagejpeg($myThumb, $thumbPath);
  171.                                  
  172.                  if (($type == "public") && ($watermark == "true")) {
  173.                      $imgMark = imagecreatefromgif("watermark.gif");
  174.  
  175.                      $dX = $mainWidth - imagesx($imgMark);
  176.                      $dY = $mainHeight - imagesy($imgMark);
  177.                      imagecopymerge($img, $imgMark, $dX, $dY, 0, 0, imagesx($imgMark), imagesy($imgMark), 40);
  178.                  
  179.                      $ext = findExtension($imagePath);
  180.    
  181.                      switch ($ext) {
  182.                        case "jpg":
  183.                           imagejpeg($img, $imagePath);  break;
  184.                        case "png":
  185.                           imagepng($img, $imagePath);   break;
  186.                      }
  187.                  }
  188.  
  189.             $details = intval(filesize($imagePath) / 1024) . " kb (" . $mainWidth . " x " . $mainHeight . ")" ;
  190.                  $id = md5($thumbPath . date("d-m-y") . time());                  
  191.  
  192.         if ($session == false)
  193.                     $q = "INSERT INTO `images`(id, image, thumb, tags, details, date, access, type, ip)
  194.                          VALUES('$id', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'public', '$ip')";
  195.                  else
  196.                  {
  197.                     if ($opt == "gallery")
  198.                         $q = "INSERT INTO `images`(id, galleryid, image, thumb, tags, details, date, access, type, ip)
  199.                             VALUES('$id', '$galleryid', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'gallery', '$ip')";
  200.                     else
  201.                         $q = "INSERT INTO `images`(id, userid, image, thumb, tags, details, date, access, type, ip)
  202.                             VALUES('$id', '$loggedId', '$imagePath', '$thumbPath', '$tags', '$details', '$date', '$lastaccess', 'member-{$type}', '$ip')";
  203.                  }  
  204.                  
  205.                  if(!($result_set = mysql_query($q))) die(mysql_error());  
  206.                  echo "<center>";
  207.                      
  208.                  echo "<center><a href=\"show-image.php?id=$id\"><img src='thumb.php?id=$id'></a></center><br>";
  209.                  echo "Imagen \"{$_FILES["image" . $i]["name"]}\" Subida correctamente <br><br>";
  210.                                
  211.                  echo "<LABEL id='title'>Enlace Directo:</LABEL><br><input type='text' size=92 onclick=\"this.select();\" value=\"{$website}/{$imagePath}\">";
  212.                  echo "<br><br>";
  213.            
  214.              echo "<LABEL id='title'>Codigo BB:</LABEL><br><input type='text' size=92 onclick=\"this.select();\" value=\"[IMG={$website}/{$imagePath}]\">";
  215.                  echo "<br><br>";
  216.            
  217.                  echo "<LABEL id='title'>Codigo BB:</LABEL><br><input type='text' size=92 onclick=\"this.select();\" value=\"[IMG]{$website}/{$imagePath}[/IMG]\">";
  218.                  echo "<br><br>";
  219.  
  220.                  echo "<LABEL id='title'>URL:</LABEL><br><input type='text' size=92 onclick=\"this.select();\"           value=\"{$website}/show-image.php?id=$id\">";
  221.  
  222.                  echo "<br><br><hr color='#233c9b'><br>";            
  223.                  echo "</center>";        
  224.                   }
  225.                  else
  226.                     echo "Lo sentimos! La imagen \"{$_FILES["image" . $i]["name"]}\" Es demasiado grande o pequeña.<br><hr color='#b1ddf6'>";  
  227.  
  228.              }
  229.              else
  230.                     echo "Usted no inserto ningun tag para la imagen \"{$_FILES["image" . $i]["name"]}\" <br><hr color='#b1ddf6'>";  
  231.        }
  232.    }
  233.  
  234. }
  235.  
  236. if ($total == 0)
  237.   echo "Lo sentimos! Debe subir al menos una imagen.";
  238.  
  239. ?>
  240. </p>
  241.   <p>&nbsp;</p>
  242.   <p> <center><a href="index.php"><img src="images/subirmas.png" width="148" height="40" border="0"></a></center></p>
  243.   <?php  include("footer.php"); ?>
  244.  
  245. </div>
  246. </center>

PD: Dejo los archivos no para que lo hagan ustedes, si no para que me puedan dar una idea más concreta de lo que tengo que hacer
__________________
WWW.LLORK.COM - El futuro es nuestro
Blog de descargas, tutoriales, guías, noticias y más.
  #3 (permalink)  
Antiguo 12/02/2012, 09:19
Avatar de Nemutagk
Colaborador
 
Fecha de Ingreso: marzo-2004
Ubicación: México
Mensajes: 2.633
Antigüedad: 20 años, 1 mes
Puntos: 406
Respuesta: Seleccionar múltiples archivos de una vez.

Bueno muy extenso tu código, pero te dejo un ejemplo....

Código PHP:
Ver original
  1. <html>
  2.     <head>
  3.         <title>Subir multiples archivos</title>
  4.     </head>
  5.     <body>
  6.         <form method="post" enctype="multiplart/from-data">
  7.             <p><input type="file" name="archivos[]" /></p>
  8.             <p><input type="file" name="archivos[]" /></p>
  9.             <p><input type="file" name="archivos[]" /></p>
  10.             <p><input type="file" name="archivos[]" /></p>
  11.             <p><input type="file" name="archivos[]" /></p>
  12.             <p><input type="file" name="archivos[]" /></p>
  13.             <p><input type="file" name="archivos[]" /></p>
  14.             <p><input type="file" name="archivos[]" /></p>
  15.             <p><inpyt type="submit" value="Subir" /></p>
  16.         </form>
  17.         <?php
  18.         if (isset($_FILES['archivos'])) {
  19.             $numFiles = count($_FILES['archivos']['tmp_name']);
  20.             for($i=0; $i<$numFiles; $i++) {
  21.                 if (is_uploaded_file($_FILES['archivos']['tmp_name'][$i])) {
  22.                     if (move_uploaded_file($_FILES['archivos']['tmp_name'][$i], $destination)) {
  23.                         echo ' el archivo se subio correctamente';
  24.                     }else {
  25.                         echo 'error al mover archivo a destino final!';
  26.                     }
  27.                 }else {
  28.                     echo 'el archivo debe subirse mediante POST';
  29.                 }
  30.             }
  31.         }
  32.         ?>
  33.     </body>
  34. </html>

El numero de campos FILES puede ser indefinida (infinitos?)
__________________
Listo?, tendría que tener 60 puntos menos de IQ para considerarme listo!!!
-- Sheldon Cooper
http://twitter.com/nemutagk
PD: No contestaré temas vía mensaje personal =)
  #4 (permalink)  
Antiguo 12/02/2012, 09:28
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Seleccionar múltiples archivos de una vez.

Cita:
Iniciado por Nemutagk Ver Mensaje
Bueno muy extenso tu código, pero te dejo un ejemplo....

Código PHP:
Ver original
  1. <html>
  2.     <head>
  3.         <title>Subir multiples archivos</title>
  4.     </head>
  5.     <body>
  6.         <form method="post" enctype="multiplart/from-data">
  7.             <p><input type="file" name="archivos[]" /></p>
  8.             <p><input type="file" name="archivos[]" /></p>
  9.             <p><input type="file" name="archivos[]" /></p>
  10.             <p><input type="file" name="archivos[]" /></p>
  11.             <p><input type="file" name="archivos[]" /></p>
  12.             <p><input type="file" name="archivos[]" /></p>
  13.             <p><input type="file" name="archivos[]" /></p>
  14.             <p><input type="file" name="archivos[]" /></p>
  15.             <p><inpyt type="submit" value="Subir" /></p>
  16.         </form>
  17.         <?php
  18.         if (isset($_FILES['archivos'])) {
  19.             $numFiles = count($_FILES['archivos']['tmp_name']);
  20.             for($i=0; $i<$numFiles; $i++) {
  21.                 if (is_uploaded_file($_FILES['archivos']['tmp_name'][$i])) {
  22.                     if (move_uploaded_file($_FILES['archivos']['tmp_name'][$i], $destination)) {
  23.                         echo ' el archivo se subio correctamente';
  24.                     }else {
  25.                         echo 'error al mover archivo a destino final!';
  26.                     }
  27.                 }else {
  28.                     echo 'el archivo debe subirse mediante POST';
  29.                 }
  30.             }
  31.         }
  32.         ?>
  33.     </body>
  34. </html>

El numero de campos FILES puede ser indefinida (infinitos?)
Gracias por responder, pero eso era exactamente lo que deseaba quitar, osea, un método como ese estoy usando ahora, y yo quiero subir varios archivos con una sola selección, asi como el hosting de imágenes imageshack.us, en el cual se seleccionan los archivos que uno desee mediante un solo selector (no sé como llamarle)

Saludos
__________________
WWW.LLORK.COM - El futuro es nuestro
Blog de descargas, tutoriales, guías, noticias y más.
  #5 (permalink)  
Antiguo 12/02/2012, 09:34
Avatar de Nemutagk
Colaborador
 
Fecha de Ingreso: marzo-2004
Ubicación: México
Mensajes: 2.633
Antigüedad: 20 años, 1 mes
Puntos: 406
Respuesta: Seleccionar múltiples archivos de una vez.

mmm te das cuenta que realmente en ningún lado indicas explicitamente lo que quieres hacer? por eso supuse que no sabias como subir multiples archivos...

Ahora, lo que hace imageshack se logra mediante Javascript, nada tiene que ver como PHP, para PHP al final se recogen (guardan) los datos de la misma forma que en un formulario tradicional
__________________
Listo?, tendría que tener 60 puntos menos de IQ para considerarme listo!!!
-- Sheldon Cooper
http://twitter.com/nemutagk
PD: No contestaré temas vía mensaje personal =)
  #6 (permalink)  
Antiguo 12/02/2012, 09:59
 
Fecha de Ingreso: diciembre-2010
Mensajes: 180
Antigüedad: 13 años, 4 meses
Puntos: 5
Respuesta: Seleccionar múltiples archivos de una vez.

Cita:
Iniciado por Nemutagk Ver Mensaje
mmm te das cuenta que realmente en ningún lado indicas explicitamente lo que quieres hacer? por eso supuse que no sabias como subir multiples archivos...

Ahora, lo que hace imageshack se logra mediante Javascript, nada tiene que ver como PHP, para PHP al final se recogen (guardan) los datos de la misma forma que en un formulario tradicional
Si, tenés razón, disculpame por hacerte responder otra cosa por expresarme mal Es javascript? Disculpen entonces que puse el TH en PHP, algún enlace que me ayude a concretar esto?

Saludos
__________________
WWW.LLORK.COM - El futuro es nuestro
Blog de descargas, tutoriales, guías, noticias y más.

Etiquetas: formulario
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 16:45.