php ziparchive readfile, такой файл не найден, ошибка

Я сталкиваюсь с этой ошибкой:

[23-Jul-2013 16:26:15 America/New_York] Предупреждение PHP: readfile(Resumes.zip): не удалось открыть поток: Нет такого файла или каталога в /home/mcaplace/public_html/download.php в строке 24

Это код:

<?php
    /*foreach($_POST['files'] as $check) {
        echo $check;}*/
    function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
    {
        $zip = new ZipArchive();
        //create the file and throw the error if unsuccessful
        if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
        exit("cannot open <$archive_file_name>\n");
        }
        //add each files of $file_name array to archive
        foreach($file_names as $files)
        {
        $zip->addFile($file_path.$files,$files);
        /*if(file_exists($file_path.$files)) //." ".$files."<br>";
            echo "yes";*/
        }
        $zip->close();
    //then send the headers to foce download the zip file
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=$archive_file_name");
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile($archive_file_name);
        exit;
    }
    //If you are passing the file names to thae array directly use the following method
    $file_names = $_POST['files'];
    //if you are getting the file name from database means use the following method
    //Include DB connection

    $archive_file_name='Resumes.zip';
    $file_path=$_SERVER['DOCUMENT_ROOT']."/resumes/";
    zipFilesAndDownload($file_names,$archive_file_name,$file_path); 
 ?>

person user2612159    schedule 23.07.2013    source источник
comment
Эта ошибка часто возникает, и для ее быстрого устранения выполните следующие действия: stackoverflow.com/a/36577021/2873507   -  person Vic Seedoubleyew    schedule 12.04.2016


Ответы (2)


У вас есть пара неправильных вещей. Во-первых, ZIPARCHIVE::CREATE неверен, это должно быть ZipArchive::CREATE или ZipArchive::OVERWRITE (перезапишите, если вы не удаляете zip-файл).

Далее ваш путь неверен. Вы не сообщаете readfile() абсолютный путь к файлу. Поэтому вам нужно указать абсолютные пути к месту сохранения zip-файла и откуда он читается.

Также я считаю маловероятным, что ваша корневая папка сайта доступна для записи. Поэтому я переместил zip в папку резюме для кода ниже. Я стараюсь держаться подальше от $_SERVER['DOCUMENT_ROOT'] и использовать функцию realpath().

И, наконец, вы должны убедиться, что в какой-либо папке, в которой создается zip-файл, есть права доступа 777.

Вот полное изменение кода

<?php
    /*foreach($_POST['files'] as $check) {
        echo $check;}*/
    function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
    {
        $zip = new ZipArchive();
        //create the file and throw the error if unsuccessful
        if ($zip->open($file_path.$archive_file_name, ZipArchive::OVERWRITE )!==TRUE) {
            exit("cannot open <$archive_file_name>\n");
        }
        //add each files of $file_name array to archive
        foreach($file_names as $files)
        {
            $zip->addFile($file_path.$files,$files);
            /*if(file_exists($file_path.$files)) //." ".$files."<br>";
                echo "yes";*/
        }
        $zip->close();
    //then send the headers to foce download the zip file
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=$archive_file_name");
        header("Pragma: no-cache");
        header("Expires: 0");
        readfile($file_path.$archive_file_name);
        exit;
    }
    //If you are passing the file names to thae array directly use the following method
    $file_names = array('test.txt');
    //if you are getting the file name from database means use the following method
    //Include DB connection

    $archive_file_name='Resumes.zip';
    $file_path=$_SERVER['DOCUMENT_ROOT']."/resumes/";

    zipFilesAndDownload($file_names,$archive_file_name,$file_path); 
 ?>
person Pyromanci    schedule 23.07.2013
comment
Та же ошибка остается даже после изменения разрешений папки. - person user2612159; 24.07.2013
comment
Странно, перед публикацией я запустил код, чтобы убедиться, что он работает. Можете ли вы распечатать пути и убедиться, что они правильно соответствуют вашей структуре папок? Также убедитесь, что zip-файл создается. - person Pyromanci; 24.07.2013
comment
Теперь здесь есть контрольный список для устранения этой частой ошибки: stackoverflow.com/a/36577021/2873507. - person Vic Seedoubleyew; 12.04.2016

У меня была аналогичная проблема с PHP 7.0, и я мог решить ее, используя решение от OHCC здесь: http://php.net/manual/de/ziparchive.open.php#118273

Он предлагал использовать оба флага OVERWRITE и CREATE одновременно.

$zip->open('i.zip', ZipArchive::OVERWRITE|ZipArchive::CREATE); 

Это решило ошибку для меня.

person patrics    schedule 07.05.2018