简体   繁体   中英

Download a zip file with PHP in a Mac computer

I am trying to create and download a zip file trough PHP. My code wrorks fine in all the posible dispositives except in mac. When a mac user tries to download the file the browser raises an "empty response" error after a few minutes. The zip file size is variable but always is near to 1.5Gb

This is the javascript function that iniciates the zip creation and the download is this one:

var peticion = ConstructorXMLHttpRequest();
if (peticion){
        disableButtons();
        peticion.open('POST', './php/createzip.php');
        peticion.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        peticion.onreadystatechange = function() {  //llama a una funcion cuando el estado cambia
            if(peticion.readyState == 4 && peticion.status == 200) {
                window.location.href = './php/download.php?az='+id_windturbine;
                enableButtons();
            }
        }

The code that create the zip file (without the bbdd queries) is thisone:

while($row = mysqli_fetch_row($result)){
         $url = '../'.$url1.$url2.'/'.$row[0];
         if ($gestor = opendir($url)){
            while (false !== ($entrada = readdir($gestor))){
                if (strpos($entrada,"full.png")!==false){
                    $files[] = $url.$entrada;
                }
            }
            closedir($gestor);
         }
    }

    $zip = new ZipArchive;
    $fecha = date('YmdGis');
    mkdir('../temp/'.$id_user.'_'.$fecha);
    $zipname = '/var/www/html/temp/'.$id_user.'_'.$fecha.'/images.zip';
    $zip->open($zipname,ZIPARCHIVE::CREATE);
    foreach ($files as $file) {
        $zip->addFile($file);
    }
    $zip->close();
    mysqli_close($db);
    $_SESSION['zipaero'.$id_windturbine]=$zipname;

When this php file ends then, as it can be seen in the js file, the download file is initiated.

include('sesion.php');
    $aero=$_GET['az'];
    $zipname = $_SESSION['zipaero'.$aero];
    if(file_exists($zipname)){
        stream($zipname);
        unset($_SESSION['zipaero'.$aero]);
    }else{
        echo "El fichero $zipname no existe";
    }
    function stream($url){
        header('Content-Description: File Transfer');
        header('Content-Type: application/zip');
        header('Content-disposition: attachment; filename="images.zip"');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($url));
        $archivo = fopen($url,"r");
        if (!($archivo===false)){
            while(!feof($archivo)){
                //imprimir contenido del archivo cada 1KB (kilobyte)
                print(fread($archivo, 1024));
                //decirle a apache que ya puede enviarlo
                ob_flush();
                flush();
            }
        }
        //cerrar el puntero al archivo
        fclose($archivo);
    }

Does any one had the same problem before and know how to solve it? I think the problem is because the createzip.php script execution last for a long time (3 minutes) but I really do not know how solve it.

Thanks in advance

--- Edit with new info---

I tried the code provided by Vivek D. twice. The first one the download started, but then it stopped at 141Mb.

ERROR1误差2

The second one raised the mentionated empty response

误差3

The erased window.location.href is './php/download.php?az='+id_windturbine as you can see in the code. (the capture is from the production server)

I don't know if this will help, but this is the code that I use for the AJAX calls.

function ConstructorXMLHttpRequest()
{
    if(window.XMLHttpRequest) /*Vemos si el objeto window posee el metodo XMLHttpRequest(Navegadores como Mozilla y Safari).*/
    {
        return new XMLHttpRequest(); //Si lo tiene, crearemos el objeto
    }

    else if(window.ActiveXObject) /*Sino tenia el metodo anterior,deberia ser el Internet Exp.*/
    {
        var versionesObj = new Array(
                                    'Msxml2.XMLHTTP.5.0',
                                    'Msxml2.XMLHTTP.4.0',
                                    'Msxml2.XMLHTTP.3.0',
                                    'Msxml2.XMLHTTP',
                                    'Microsoft.XMLHTTP');

        for (var i = 0; i < versionesObj.length; i++)
        {
            try
                {
                    return new ActiveXObject(versionesObj[i]);
                }
                catch (errorControlado)
                {

                }
        }
    }
    throw new Error("No se pudo crear el objeto XMLHttpRequest");
}

Try the below code.

function stream($url){
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: filename=image.zip');
        header("Content-Transfer-Encoding: Binary");
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($url));
        $archivo = fopen($url,"r");
        if (!($archivo===false)){
            while(!feof($archivo)){ 
                print(fread($archivo, 1024)); 
                flush();
            }
        }
        //cerrar el puntero al archivo
        fclose($archivo);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM