在Ajax中定义用于生成zip PHP的标头

在Ajax中定义用于生成zip PHP的标头,php,jquery,ajax,fpdf,ziparchive,Php,Jquery,Ajax,Fpdf,Ziparchive,我正在尝试使用ZipArchive类生成zip文件,其中包含使用FPDF库生成的pdf文件 我正在使用ajax和PHP来实现这一点,问题是我不知道如何在ajax中设置头以强制在浏览器中下载。 文件内容在我的HTML中读取,而不是发送回zip下载 PHP脚本: <?php require('config/config.php'); require('fpdf/fpdf.php'); if(!isset($_SESSION)) { session_start(); } $outpu

我正在尝试使用ZipArchive类生成zip文件,其中包含使用FPDF库生成的pdf文件

我正在使用ajax和PHP来实现这一点,问题是我不知道如何在ajax中设置头以强制在浏览器中下载。 文件内容在我的HTML中读取,而不是发送回zip下载

PHP脚本:

<?php
require('config/config.php');
require('fpdf/fpdf.php');

if(!isset($_SESSION))
{
    session_start();
}

$output = "";

if(isset($_SESSION['user']))
{
    $currentTime = time();
    if($currentTime < $_SESSION['expire'])
    {
        if(!empty($_POST['candidacy']))
        {
            $stmt = $cnx->prepare('SELECT * FROM candidacies WHERE id = :candidacy');
            $stmt->bindValue(':candidacy', $_POST['candidacy'], PDO::PARAM_INT);
            $stmt->execute();

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
            var_dump($result);
            foreach($result as $key => $value)
            {
                $nameUser = $value['lastName']." ".$value['firstName'];
                $emailUser = $value['email'];
            }

            $pdf = new FPDF();

            $pdf->AliasNbPages();
            $pdf->AddPage();

            $pdf->Image('img/candidacy.jpg',10,6,25);

            $pdf->SetFont('Times','',13);

            $pdf->Cell(60);
            $pdf->Cell(80,10, utf8_decode('Candidacy'),1,1,'C');
            $pdf->ln();

            $pdf->Cell(60);
            $pdf->Cell(80,10, date("d/m/Y"),1,1,'C');
            $pdf->ln();

            $pdf->Cell(50,10,'Nom complet : ', 0,0);
            $pdf->Cell(65,10, utf8_decode($nameUser), 0,1);

            $pdf->Cell(50,10, 'Email : ', 0,0);
            $pdf->Cell(100,10, utf8_decode($emailUser), 0,1);

            $file = 'CCandidacy-'.$nameUser.'.pdf';

            $pdf->Output('F', $file);

            if(extension_loaded('zip'))
            {
                $zip = new ZipArchive();

                $zip_name = md5(random_bytes(64)).".zip";

                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
                {
                    $output .= "Impossible to create zip !";
                }

                $zip->addFile($file);

                $zip->close();

                if(file_exists($zip_name))
                {
                    header('Content-type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name);
                    header('Content-Length: ' . filesize($zip_name));

                    readfile($zip_name);

                    unlink($zip_name);
                }
            }
            else
            {
                $output .= "Check extension !";
            }

            return $zip_name;
        }
    }
}
else
{
    unset($_SESSION['user']);
    session_destroy();
    header('Location: ../login.php');
    exit(0);
}

一旦ajax调用就绪,您可以使用location.href重定向到生成的zip文件(这意味着您的zip文件也就绪)

从PHP返回zip文件的url,然后使用下面的

function zipExtract(candidacy)
{
    var content = {};
    content['candidacy'] = candidacy;

    $.post('zipCandidacy.php', content, function(data)
    {
       location.href=data;
    });
}

我认为你不需要下面的内容,但写下来只是为了以防万一

请记住,在ajax中不设置头。您可以使用header()函数在php文件中设置头

zip的mime类型(如果服务器无法满足您的zip请求,请下载)

application/zip、application/octet流

在PHP代码中

// We'll be outputting a ZIP
header('Content-Type: application/zip, application/octet-stream');

// It will be called myzip.zip
header('Content-Disposition: attachment; filename="myzip.zip"');

// your PHP code and FPDF stuff

我终于找到了解决办法!正如您向我指出的那样,Oliver,AJAX并不是我想要的定义标题的最佳方式。因此,在执行onclick事件时,我重定向到php处理页面,以便继续下载zip文件

<?php
require('config/config.php');
require('fpdf/fpdf.php');

if(!isset($_SESSION))
{
    session_start();
}

$output = "";

if(isset($_SESSION['user']))
{
    $currentTime = time();
    if($currentTime < $_SESSION['expire'])
    {
        if(!empty($_GET['candidacy']))
        {
            $stmt = $cnx->prepare('SELECT * FROM candidacies WHERE id = :candidacy');
            $stmt->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $stmt->execute();

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach($result as $key => $value)
            {
                switch($value['zipcode'])
                {
                    case "North":
                        $zipcode = "Nord";
                        break;
                    case "South":
                        $zipcode = "Sud";
                        break;
                    case "East":
                        $zipcode = "Est";
                        break;
                    case "West":
                        $zipcode = "Ouest";
                        break;
                }

                switch($value['transportMeans'])
                {
                    case "onFoot":
                        $transportMeans = "À pied";
                        break;
                    case "vehicle":
                        $transportMeans = "Voiture";
                        break;
                    case "bike":
                        $transportMeans = "Moto";
                        break;
                    case "bus":
                        $transportMeans = "Bus";
                        break;
                    case "carpool":
                        $transportMeans = "Covoiturage";
                        break;
                    case "bicycle":
                        $transportMeans = "Vélo";
                        break;
                }

                switch($value['candidacyType'])
                {
                    case "mysteryCustomer":
                        $candidacyType = "Client Mystère";
                        break;
                    case "investigationUnit":
                        $candidacyType = "Chargé d'enquêtes";
                        break;
                    case "investigators":
                        $candidacyType = "Enquêteurs/Enquêtrices";
                        break;
                }

                $nameUser = $value['lastName']." ".$value['firstName'];
                $age = $value['age'];
                $employment = $value['employment'];
                $zipcode = $zipcode;
                $transportMeans = $transportMeans;
                $scheduleRange = $value['scheduleRange'];
                $emailUser = $value['email'];
                $phoneNumber = $value['phoneNumber'];
                $candidacyType = $candidacyType;
                $coveringLetter = $value['coveringLetter'];
                $curriculumVitae = $value['curriculumVitae'];
                $createdAt = $value['createdAt'];
            }

            $pdf = new FPDF();

            $pdf->AliasNbPages();
            $pdf->AddPage();

            $pdf->Image('img/candidacy.jpg',10,6,25);

            $pdf->SetFont('Times','',13);

            $pdf->Cell(60);
            $pdf->Cell(80,10, utf8_decode('Candidature'),1,1,'C');
            $pdf->ln();

            $pdf->Cell(60);
            $pdf->Cell(80,10, $createdAt,1,1,'C');
            $pdf->ln();

            $pdf->Cell(50,10, 'Nom complet : ', 0,0);
            $pdf->Cell(65,10, utf8_decode($nameUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('Âge : '),0,0);
            $pdf->Cell(65,10, utf8_decode($age), 0,1);

            $pdf->Cell(50,10,'Profession : ',0,0);
            $pdf->Cell(65,10, utf8_decode($employment), 0,1);

            $pdf->Cell(50,10, 'Secteur : ',0,0);
            $pdf->Cell(65,10, utf8_decode($zipcode), 0,1);

            $pdf->Cell(50,10, 'Moyen de transport :',0,0);
            $pdf->Cell(65,10, utf8_decode($transportMeans), 0,1);

            $pdf->Cell(50,10, 'Horaires : ',0,0);
            $pdf->Cell(65,10, utf8_decode($scheduleRange), 0,1);

            $pdf->Cell(50,10, 'Email : ', 0,0);
            $pdf->Cell(100,10, utf8_decode($emailUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('N° de téléphone : '),0,0);
            $pdf->Cell(65,10, utf8_decode($phoneNumber), 0,1);

            $pdf->Cell(50,10, 'Candidature : ',0,0);
            $pdf->Cell(65,10, utf8_decode($candidacyType), 0,1);

            $file = 'Candidature-'.$nameUser.'.pdf';

            $pdf->Output('F', $file);

            $files = array($file, "candidatures/".$coveringLetter, "candidatures/".$curriculumVitae);

            if(extension_loaded('zip'))
            {
                $zip = new ZipArchive();

                $zip_name = md5(random_bytes(64)).".zip";

                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
                {
                    $error .= "Création impossible du zip !";
                }

                foreach($files as $content)
                {
                    $zip->addFile($content);
                }

                $zip->close();

                if(file_exists($zip_name))
                {
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name);
                    header('Content-Length: ' . filesize($zip_name));

                    readfile($zip_name);

                    unlink($zip_name);
                }
            }
            else
            {
                $error .= "Vérifier l'extension !";
            }

            $query = $cnx->prepare('UPDATE candidacies SET lastExport = now() WHERE id = :candidacy');
            $query->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $query->execute();
        }
    }
}
else
{
    unset($_SESSION['user']);
    session_destroy();
    header('Location: ../login.php');
    exit(0);
}


function zipExtract(candidacy)
{
    window.location.href = ("../zipCandidacy.php?candidacy="+candidacy);
}

谢谢你的回答@Oliver!问题是我在js中的函数与onclick事件相关。我有一份候选名单,我建议用zip格式下载候选名单的内容。在这个onclick事件中,我检索已单击候选资格的id。这就是我使用ajaxIf的原因。如果我理解得很好,我在PHP中添加了“return$zip_name”,然后,我修改了我的ajax,这是正确的??嘿,是的,这是正确的,确保你用唯一的代码命名你的zip文件,就像有超过一个人使用你的应用程序/网站一样,你最终会被覆盖文件。祝你好运如果您需要帮助,请询问更多:)嗯,我编辑了我的脚本,并尝试了它,问题是所有内容从现在起都在url中。zip下载的标题没有显示@OliverI尝试了另一种方式,但仍然没有显示:/function zipExtract(candidate){var content={};content['candidate']=candidate;$.ajax({type:“POST”,url:“zipCandidacy.php”,contentType:“application/zip”,数据:内容,成功:函数(data){$('#zipContent').html(data);},})}}您不能使用AJAX直接将文件下载到磁盘。响应将始终返回到JavaScript,而不是用户的设备。您必须使用常规回发(如果需要,您可以使用JS伪造表单提交),或者将zip保存到服务器,然后让AJAX返回一个URL,然后您可以使用JavaScript将浏览器导航到该URL。这些都是您的选项。完美!location.href部分必须放在前端,尽管它可能可以正常工作。祝您好运,坚持并享受:)啊哈谢谢你的支持@Oliver!:)如果你看到实现我愿望的另一种方式,请毫不犹豫地提出!
<?php
require('config/config.php');
require('fpdf/fpdf.php');

if(!isset($_SESSION))
{
    session_start();
}

$output = "";

if(isset($_SESSION['user']))
{
    $currentTime = time();
    if($currentTime < $_SESSION['expire'])
    {
        if(!empty($_GET['candidacy']))
        {
            $stmt = $cnx->prepare('SELECT * FROM candidacies WHERE id = :candidacy');
            $stmt->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $stmt->execute();

            $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

            foreach($result as $key => $value)
            {
                switch($value['zipcode'])
                {
                    case "North":
                        $zipcode = "Nord";
                        break;
                    case "South":
                        $zipcode = "Sud";
                        break;
                    case "East":
                        $zipcode = "Est";
                        break;
                    case "West":
                        $zipcode = "Ouest";
                        break;
                }

                switch($value['transportMeans'])
                {
                    case "onFoot":
                        $transportMeans = "À pied";
                        break;
                    case "vehicle":
                        $transportMeans = "Voiture";
                        break;
                    case "bike":
                        $transportMeans = "Moto";
                        break;
                    case "bus":
                        $transportMeans = "Bus";
                        break;
                    case "carpool":
                        $transportMeans = "Covoiturage";
                        break;
                    case "bicycle":
                        $transportMeans = "Vélo";
                        break;
                }

                switch($value['candidacyType'])
                {
                    case "mysteryCustomer":
                        $candidacyType = "Client Mystère";
                        break;
                    case "investigationUnit":
                        $candidacyType = "Chargé d'enquêtes";
                        break;
                    case "investigators":
                        $candidacyType = "Enquêteurs/Enquêtrices";
                        break;
                }

                $nameUser = $value['lastName']." ".$value['firstName'];
                $age = $value['age'];
                $employment = $value['employment'];
                $zipcode = $zipcode;
                $transportMeans = $transportMeans;
                $scheduleRange = $value['scheduleRange'];
                $emailUser = $value['email'];
                $phoneNumber = $value['phoneNumber'];
                $candidacyType = $candidacyType;
                $coveringLetter = $value['coveringLetter'];
                $curriculumVitae = $value['curriculumVitae'];
                $createdAt = $value['createdAt'];
            }

            $pdf = new FPDF();

            $pdf->AliasNbPages();
            $pdf->AddPage();

            $pdf->Image('img/candidacy.jpg',10,6,25);

            $pdf->SetFont('Times','',13);

            $pdf->Cell(60);
            $pdf->Cell(80,10, utf8_decode('Candidature'),1,1,'C');
            $pdf->ln();

            $pdf->Cell(60);
            $pdf->Cell(80,10, $createdAt,1,1,'C');
            $pdf->ln();

            $pdf->Cell(50,10, 'Nom complet : ', 0,0);
            $pdf->Cell(65,10, utf8_decode($nameUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('Âge : '),0,0);
            $pdf->Cell(65,10, utf8_decode($age), 0,1);

            $pdf->Cell(50,10,'Profession : ',0,0);
            $pdf->Cell(65,10, utf8_decode($employment), 0,1);

            $pdf->Cell(50,10, 'Secteur : ',0,0);
            $pdf->Cell(65,10, utf8_decode($zipcode), 0,1);

            $pdf->Cell(50,10, 'Moyen de transport :',0,0);
            $pdf->Cell(65,10, utf8_decode($transportMeans), 0,1);

            $pdf->Cell(50,10, 'Horaires : ',0,0);
            $pdf->Cell(65,10, utf8_decode($scheduleRange), 0,1);

            $pdf->Cell(50,10, 'Email : ', 0,0);
            $pdf->Cell(100,10, utf8_decode($emailUser), 0,1);

            $pdf->Cell(50,10, utf8_decode('N° de téléphone : '),0,0);
            $pdf->Cell(65,10, utf8_decode($phoneNumber), 0,1);

            $pdf->Cell(50,10, 'Candidature : ',0,0);
            $pdf->Cell(65,10, utf8_decode($candidacyType), 0,1);

            $file = 'Candidature-'.$nameUser.'.pdf';

            $pdf->Output('F', $file);

            $files = array($file, "candidatures/".$coveringLetter, "candidatures/".$curriculumVitae);

            if(extension_loaded('zip'))
            {
                $zip = new ZipArchive();

                $zip_name = md5(random_bytes(64)).".zip";

                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE)
                {
                    $error .= "Création impossible du zip !";
                }

                foreach($files as $content)
                {
                    $zip->addFile($content);
                }

                $zip->close();

                if(file_exists($zip_name))
                {
                    header('Content-Type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name);
                    header('Content-Length: ' . filesize($zip_name));

                    readfile($zip_name);

                    unlink($zip_name);
                }
            }
            else
            {
                $error .= "Vérifier l'extension !";
            }

            $query = $cnx->prepare('UPDATE candidacies SET lastExport = now() WHERE id = :candidacy');
            $query->bindValue(':candidacy', $_GET['candidacy'], PDO::PARAM_INT);
            $query->execute();
        }
    }
}
else
{
    unset($_SESSION['user']);
    session_destroy();
    header('Location: ../login.php');
    exit(0);
}


function zipExtract(candidacy)
{
    window.location.href = ("../zipCandidacy.php?candidacy="+candidacy);
}