Foros del Web » Programando para Internet » PHP »

Descomprimir zip al subir el fichero

Estas en el tema de Descomprimir zip al subir el fichero en el foro de PHP en Foros del Web. Buenas. Estaba encargandome de un upload de ficheros, que funciona perfectamente como se puede ver en el codigo que muestro. Código: <?php $dir = "eulen"; ...
  #1 (permalink)  
Antiguo 06/05/2010, 04:13
 
Fecha de Ingreso: mayo-2010
Mensajes: 6
Antigüedad: 13 años, 11 meses
Puntos: 1
Descomprimir zip al subir el fichero

Buenas. Estaba encargandome de un upload de ficheros, que funciona perfectamente como se puede ver en el codigo que muestro.

Código:
<?php 


$dir = "eulen"; //Change this to the correct dir  RELATIVE TO WHERE THIS SCRIPT IS, or /full/path/

//MIME types to allow, Gif, jpeg, zip ::Edit this to your liking 
$types = array("application/pdf","image/png","image/x-png","audio/wav","image/gif","image/jpeg", "image/png", "image/pjpeg","application/x-zip-compressed","application/zip"); 
    
// Nothing to edit below here.

//Function to do a directory listing
//function scandir($dirstr) {
//	echo "<pre>\n";
//	passthru("ls -l -F $dirstr 2>&1 ");
//	echo "</pre>\n";
//}

//Check to determine if the submit button has been pressed 
if((isset($_POST['submit']))){ 

	//Shorten Variables 
	$tmp_name = $_FILES['upload']['tmp_name']; 
	$new_name = $_FILES['upload']['name']; 
	$path = $_POST['subdir'];
	$fullpath = "$dir$path/";
	$fullpath = str_replace("..", "", str_replace("\.", "", str_replace("//", "/", $fullpath)));
	$clean_name = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($new_name) ) ) );


// lets see if we are uploading a file or doing a dir listing
	if(isset($_POST['Dir'])){
		echo "Directorio asignado en $fullpath\n";
		scandir("$fullpath");
		}else{




		//Check MIME Type 
		if ((in_array($_FILES['upload']['type'], $types)) and (!file_exists($fullpath.$clean_name))){ 

			// create a sub-directory if required
			if (!is_dir($fullpath)){
				mkdir("$fullpath", 0755);
			}
			//Move file from tmp dir to new location 
			move_uploaded_file($tmp_name,$fullpath . $clean_name); 

                        $filesize = $_FILES['userfile']['size'];

 
			echo "$clean_name of {$_FILES['upload']['size']} bytes fue correctamente guardado en $fullpath";


		}else{ 
          
			//Print Error Message 
			echo "<small>File <strong><em>{$_FILES['upload']['name']}</em></strong> No se pudo guardar - tipo de archivo incorrecto o ya existente</small><br/>"; 
			//Debug 
			$name =  $_FILES['upload']['name']; 
			$type =    $_FILES['upload']['type']; 
			$size =    $_FILES['upload']['size']; 
			$tmp =     $_FILES['upload']['name']; 
    
			echo "Name: $name<br />Type: $type<br />Size: $size<br />Tmp: $tmp";
                        

		} 
      
	} 
} else { 

} ?> 
         <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> 
      
<fieldset> 
<legend>Sube archivos</legend> 
<p align = "left">Elegir otro directorio por defecto <input type="checkbox" name="Dir" value="on" /><br />
Fichero a subir <input type="file" name="upload" /> <br />
Guardar en/Cambiar directorio por defecto: <input type="text" name="subdir" value="<?php $path = $_POST['subdir']; echo "$path";?>" /> (Puede estar en blanco) **El directorio será creado si no existe<br />
<input type="submit" name="submit" value="Subir fichero/cambiar carpeta" /> 
</fieldset> 
</form>
</body>
</html>


El caso, es que estaba intentando añadir la condición de que si un archivo era un zip, que lo descomprimiese al subirlo, pero por más que lo intento, no consigo que esa parte de la función funcione bien, el caso, me vendría bien ayuda para saber en que parte implementarla para evitar problemas.

Vendría siendo esto la parte que trabaja con el zip.

Código:
<?php
    $zip = zip_open($_FILES['upload']['tmp_name']);
    while($zip_entry = zip_read($zip)) {
        $entry = zip_entry_open($zip,$zip_entry);
        $filename = zip_entry_name($zip_entry);
        $target_dir = $dir.substr($filename,0,strrpos($filename,'/'));
        $filesize = zip_entry_filesize($zip_entry);
        if (is_dir($target_dir) || mkdir($target_dir)) {
            if ($filesize > 0) {
                $contents = zip_entry_read($zip_entry, $filesize);
                file_put_contents($dir.$filename,$contents);
            }
        }
    }
?>
He probado varias cosas pero no consigo que me funcione ¿Qué debería hacer?
  #2 (permalink)  
Antiguo 06/05/2010, 06:19
 
Fecha de Ingreso: mayo-2010
Mensajes: 6
Antigüedad: 13 años, 11 meses
Puntos: 1
Respuesta: Descomprimir zip al subir el fichero

Al final he conseguido solucionarlo, comparto con vosotros este uploader con descomprensor en caso de ser un zip.

Código:
<?php 
/* Simple Upload manager
Script Version 0.4, copyright RRWH.com 2004

This script is distributed under the licence conditions on the website http://rrwh.com/scripts.php

This script is a simple interface to allow you to upload files to a configured directory on your server.  It will additionally automatically create sub-directories if you want it to.  Additionally, It will let you do a directory listing of the base directory or any specified sub-directory.

You only need to modify the $password and $dir variable and ensure that the directory exists on the server and the permission is set to 777

You may want to modify the $types if you wish to allow other file types to be uploaded - Be careful not to allow dangerous files to be uploaded to your server.

*/



$dir = "/var/www/eulen"; //Change this to the correct dir  RELATIVE TO WHERE THIS SCRIPT IS, or /full/path/

//MIME types to allow, Gif, jpeg, zip ::Edit this to your liking 
$types = array("application/pdf","image/png","image/x-png","audio/wav","image/gif","image/jpeg", "image/png", "image/pjpeg","application/x-zip-compressed","application/zip"); 
    
// Nothing to edit below here.

//Function to do a directory listing
//function scandir($dirstr) {
//	echo "<pre>\n";
//	passthru("ls -l -F $dirstr 2>&1 ");
//	echo "</pre>\n";
//}

//Check to determine if the submit button has been pressed 
if((isset($_POST['submit']))){ 

	//Shorten Variables 
	$tmp_name = $_FILES['upload']['tmp_name']; 
	$new_name = $_FILES['upload']['name']; 
	$path = $_POST['subdir'];
	$fullpath = "$dir$path/";
	$fullpath = str_replace("..", "", str_replace("\.", "", str_replace("//", "/", $fullpath)));
	$clean_name = ereg_replace("[^a-z0-9._]", "", str_replace(" ", "_", str_replace("%20", "_", strtolower($new_name) ) ) );


// lets see if we are uploading a file or doing a dir listing
	if(isset($_POST['Dir'])){
		echo "Directorio asignado en $fullpath\n";
		scandir("$fullpath");
		}else{




		//Check MIME Type 

		if ((in_array($_FILES['upload']['type'], $types)) and (!file_exists($fullpath.$clean_name))){ 
                          
			// create a sub-directory if required
			if (!is_dir($fullpath)){
				mkdir("$fullpath", 0755);
			}
			//Move file from tmp dir to new location 

      


			move_uploaded_file($tmp_name,$fullpath . $clean_name); 

                        $filesize = $_FILES['userfile']['size'];

 
			echo "$clean_name de {$_FILES['upload']['size']} bytes fue correctamente guardado en $fullpath";
                        

                    //A partir de aqui verifica si el archivo es un zip para descomprimirlo
                              $file_basename = substr($clean_name, 0, strripos($clean_name, '.')); // strip extention
      			      $file_ext      = substr($clean_name, strripos($clean_name, '.'));
                         if($file_ext = ".zip")
                         {
                            $zip = new ZipArchive;
				if ($zip->open($clean_name) === TRUE) {
   				 $zip->extractTo($dir);
   				 $zip->close();
   				 echo ' ok ';
					} else {
    					echo ' failed ';
				    }


                                  }
                         

                             



		}else{ 
          
			//Print Error Message 
			echo "<small>File <strong><em>{$_FILES['upload']['name']}</em></strong> No se pudo guardar - tipo de archivo incorrecto o ya existente</small><br/>"; 
			//Debug 
			$name =  $_FILES['upload']['name']; 
			$type =    $_FILES['upload']['type']; 
			$size =    $_FILES['upload']['size']; 
			$tmp =     $_FILES['upload']['name']; 
    
			echo "Name: $name<br />Type: $type<br />Size: $size<br />Tmp: $tmp";
                        

		} 
      
	} 
} else { 

} ?> 
         <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data"> 
      
<fieldset> 
<legend>Sube archivos</legend> 
<p align = "left">Elegir otro directorio por defecto <input type="checkbox" name="Dir" value="on" /><br />
Fichero a subir <input type="file" name="upload" /> <br />
Guardar en/Cambiar directorio por defecto: <input type="text" name="subdir" value="<?php $path = $_POST['subdir']; echo "$path";?>" /> (Puede estar en blanco) **El directorio será creado si no existe<br />
<input type="submit" name="submit" value="Subir fichero/cambiar carpeta" /> 
</fieldset> 
</form>
</body>
</html>

Etiquetas: descomprimir, fichero, subir, zip
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

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 05:30.