3

Lo que quiero realizar es que se cree un archivo de .rar o .zip y después se descargue en la computadora de mi usuario y se elimine de mi servidor una vez que se haya descargado, hasta ahorita ya me hace la conversión de mi carpeta a un comprimido pero lo deja en mi carpeta local y yo quiero que eso se descargue automáticamente y se elimine una vez descargado.

Aquí esta el código de la conversión de mi carpeta a .zip

<?php

$zip = new ZipArchive();

$filename = 'test.zip';


if($zip->open($filename,ZIPARCHIVE::CREATE)===true) {
// Get real path for our folder
$rootPath = realpath('../walkingdead');

// Initialize archive object
$zip = new ZipArchive();
$zip->open('walking.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

// Create recursive directory iterator
/** @var SplFileInfo[] $files */
$files = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator($rootPath),
    RecursiveIteratorIterator::LEAVES_ONLY
);

foreach ($files as $name => $file)
{
    // Skip directories (they would be added automatically)
    if (!$file->isDir())
    {
        // Get real and relative path for current file
        $filePath = $file->getRealPath();
        $relativePath = substr($filePath, strlen($rootPath) + 1);

        // Add current file to archive
        $zip->addFile($filePath, $relativePath);
    }
}

// Zip archive will be created only after closing object
$zip->close();
}

Aquí esta el código que me redirecciona a esa pagina .php

    function thewalking() {
        var descarga = document.getElementById("descarga");
        descarga.style.animationName = "animacionL";
        descarga.style.animationDuration = "3s";
        document.getElementById('descarga').innerHTML = "<center><label >Comic: The Walking Dead</label></center><a id=btndescargar style=text-decoration:none; href=ComicsyMangas/comics/walking_descargar/descargar.php >Descargar</a><br><a id=btnonline style=text-decoration:none;cursor:pointer; onclick=alerta() >Online </a><br><label>Tamaño (Archivo): </label><label>2MB</label><br><label>Numero de Paginas: 792pag.</label><br><label>Autor: Stephen King</label>";
    }

Hasta ahí ya hace el empaquetado, pero no se inicia la descarga de mi archivo .zip y eso me gustaría saber como se hace, también que me digan como borrar el archivo .zip creado automáticamente, una vez que se haya descargado mi archivo en la pc de mi cliente.

PD: Estoy usando la librería nativa de php ZipArchive

2 respuestas 2

3

Teniendo el nombre del archivo:

$filename = 'test.zip';


¿Cómo hacer que un script PHP envíe un archivo para ser descargado?

Se presentan 2 formas: una más directa y sencilla y otra que se encarga de verificar errores, principalmente con archivos grandes que podrían exceder el límite de memoria, y de ofrecer reestablecer una descarga interrumpida. En ambas, es muy importante que el script no escriba nada, ni siquiera una línea en blanco antes del <?php, ya que se envían encabezados HTTP.

  1. Forma sencilla

    Funciona perfecto para la gran mayoría de los archivos, mientras el tamaño del mismo no exceda el límite de memoria.

      //Sin notificaciones, y que el server no comprima
    @ini_set('error_reporting', E_ALL & ~ E_NOTICE);
    @ini_set('zlib.output_compression', 'Off');
      //Encabezados para archivos .zip
    header('Content-Type: application/zip');
    header('Content-Transfer-Encoding: Binary');
      //El nombre predeterminado que verá el cliente
    header('Content-disposition: attachment; filename="' . basename($filename) . '"');
      //Que no haya límite en la ejecución del script
    @set_time_limit(0);
    
      //Imprime el contenido del archivo
    readfile($filename);
    



  1. Descargar el archivo por bloques, permitiendo resumir descargas mediante http_range*

    //esconder notificaciones
    @ini_set('error_reporting', E_ALL & ~ E_NOTICE);
    //que el server no comprima
    @apache_setenv('no-gzip', 1);
    @ini_set('zlib.output_compression', 'Off');
    
    // parsear el nombre del archivo
    $path_parts = pathinfo($filename);
    $file_name  = $path_parts['basename'];
    $file_ext   = $path_parts['extension'];
    $file_path  = $file_name; //Si se descarga de otra ubicación, cambiar por: $file_path = './carpeta/descargas/' . $file_name;
    
    $is_attachment = true; //Como adjunto (cambiar a false si es un stream, por ej. audio o video)
    
    // existe el archivo?
    if (is_file($file_path))
    {
        $file_size  = filesize($file_path);
        $file = @fopen($file_path,"rb");
        if ($file)
        {
            // encabezados, y sin caché
            header("Pragma: public");
            header("Expires: -1");
            header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0");
    
            if ($is_attachment)
                    header("Content-Disposition: attachment; filename=\"$file_name\"");
            else
                    header('Content-Disposition: inline;');
    
            // mime type según la extensión (agregar otra si falta)
            $ctype_default = "application/octet-stream";
            $content_types = array(
                    "exe" =--> "application/octet-stream",
                    "zip" => "application/zip",
                    "mp3" => "audio/mpeg",
                    "mpg" => "video/mpeg",
                    "avi" => "video/x-msvideo",
            );
            $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default;
            header("Content-Type: " . $ctype);
    
            // http_range si hay gestión de descarga
            $range = '';
            if(isset($_SERVER['HTTP_RANGE']))
            {
                list($size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);
                if ($size_unit == 'bytes')
                {
                    list($range, $extra_ranges) = explode(',', $range_orig, 2);
                }
                else
                {
                    header('HTTP/1.1 416 Requested Range Not Satisfiable');
                    exit;
                }
            }
            list($seek_start, $seek_end) = explode('-', $range, 2);
            $seek_end   = (empty($seek_end)) ? ($file_size - 1) : min(abs(intval($seek_end)),($file_size - 1));
            $seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);
            if ($seek_start > 0 || $seek_end < ($file_size - 1))
            {
                header('HTTP/1.1 206 Partial Content');
                header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$file_size);
                header('Content-Length: '.($seek_end - $seek_start + 1));
            }
            else
              header("Content-Length: $file_size");
    
            header('Accept-Ranges: bytes');
    
            set_time_limit(0);
            fseek($file, $seek_start);
    
            // imprimir el archivo
            while(!feof($file)) 
            {
                print(@fread($file, 1024*8));     //leer 8KB
                ob_flush();
                flush();
                if (connection_status()!=0) 
                {
                    @fclose($file);
                    exit; //error
                }
            }
    
            // terminó OK
            @fclose($file);
        }
        else 
        {
            // no se pudo abrir el archivo
            header("HTTP/1.0 500 Internal Server Error");
        }
    }
    else
    {
        // no existe el archivo
        header("HTTP/1.0 404 Not Found");
    }
    exit;
    
    /**
     * Copyright 2012 Armand Niculescu - media-division.com
     * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
     * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
     * 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
     * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     */
    

    *Versión modificada del código de Armand Niculescu

3
  • oye @Mariano, ya realice la primera opción que sonaba muy fácil y sencilla, pero me descarga un archivo .zip que no tiene ningún elemento dentro y cuando lo intento abrir me marca error $filename="walkingdead.zip"; readfile($filename);
    – David
    el 24 ago. 2016 a las 18:41
  • si lo eh abierto de manera local se guarda uno que si se abre pero el que se descarga no tiene archivos y pues marca error, entonces localmente se almacena pero no se descarga ese sino uno vació
    – David
    el 24 ago. 2016 a las 20:56
  • @David Estás creando el objeto $zip 2 veces. Borrá las líneas 13 y 14 de tu script. Y asegurate de que tu script tenga permisos de escritura, y que se pueda escribir en la carpeta en la que creas el archivo zip.
    – Mariano
    el 25 ago. 2016 a las 10:30
1

Complementando la respuesta de Mariano, te diré como puedes borrar un archivo del servidor.

Esto lo puedes lograr mediante una función nativa de PHP llamada unlink, que te permite eliminar archivos del servidor sin necesidad de hacer una conexión FTP. Lo único que se necesita es especificar la ruta al archivo que se quiere eliminar y listo y saber que es una función booleana que nos regresa los siguientes valores:

Devuelve TRUE en caso de éxito o FALSE en caso de error.

Supongamos que tenemos un archivo que queremos eliminar en la siguiente ruta: C:\user\pepito\prueba.txt. Bien, pues para poderla borrar sería de la siguiente manera:

<?php
   $path = 'C:\user\pepito\';
   $filename = 'prueba.txt';
   $fullpath = $path.$filename;

   if (!unlink($fullpath)) {
     echo 'Error al borrar el archivo llamado '.$filename;
   } else {
     echo 'Archivo '.$filename.' borrado exitosamente.';
   }
?>

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.