How to download a .zip file from the server to the client via php?

4

What I want to do is to create a .rar or .zip file and then download it to my user's computer and delete it from my server once it has been downloaded, until now I have the conversion of my folder to a tablet but it leaves it in my local folder and I want that to be downloaded automatically and deleted once downloaded.

Here is the code for converting my folder to .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();
}

Here is the code that redirects me to that page .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>";
    }

Until then the packaging is done, but the download of my .zip file does not start and I would like to know how it is done, also tell me how to delete the .zip file created automatically, once my file has been downloaded. file on my client's PC.

PS: I'm using the native ZipArchive php library

    
asked by David 24.08.2016 в 03:51
source

2 answers

3

Having the name of the file:

$filename = 'test.zip';


How to make a PHP script send a file to be downloaded?

Two forms are presented: a more direct and simple and another that is responsible for checking errors, mainly with large files that could exceed the memory limit, and offer to restore an interrupted download. In both, it is very important that the script does not write anything, not even a blank line before <?php , since HTTP headers .

  • Simple form

    It works perfect for the vast majority of files, as long as the size does not exceed the memory limit.

      //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);
    

  • Download the file in blocks, allowing summary downloads using 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.
     */
    

    * Modified version of the code of Armand Niculescu

  • answered by 24.08.2016 в 10:41
    2

    Complementing Mariano's answer, I will tell you how you can delete a file from the server.

    This can be achieved through a native PHP function called unlink , which allows you to delete files from the server without the need to make an FTP connection. The only thing that is needed is to specify the path to the file that you want to delete and go and know that it is a Boolean function that returns the following values:

      

    Returns TRUE on success or FALSE on error.

    Suppose we have a file that we want to delete in the following path: C:\user\pepito\prueba.txt . Well, to be able to erase it would be as follows:

    <?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.';
       }
    ?>
    
        
    answered by 25.08.2016 в 01:19