Pzp ZipArchive保存zip位置

时间:2019-03-10 17:16:48

标签: php ziparchive

我正在将Ajax与wordpress一起使用以导出zip文件。该代码效果很好,但是它在2个不同的位置,我的桌面(作为默认浏览器下载位置)以及运行此插件代码的wordpress / wp-admin目录中下载了zip文件。我不希望将其下载到wp-admin位置,如何防止这种情况?

//ajax

$('.btn').on('click', function(){

    var postData = [
        {name: 'action', value: 'foo_export_playlist'},
        {name: 'playlist_id', value: playlist_id},
        {name: 'playlist_title', value: playlist_title}
    ];

    $.ajax({
        url: ajax_url,
        type: 'post',
        data: postData,
        dataType: 'json',
    }).done(function(response){

           if(response.zip) {
            location.href = response.zip;
        }

    }).fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR.responseText, textStatus, errorThrown);
    }); 

    return false;

});



//php

function foo_export_playlist(){

    // create zip file
    $zipname = 'foo.zip';
    $zip = new ZipArchive;
    $zip->open($zipname, ZipArchive::CREATE);


    // create a temporary file
    $size = 1 * 1024 * 1024;
    $fp = fopen('php://temp/maxmemory:$size', 'w');
    if (false === $fp) {
        die('Failed to create temporary file');
    }

  $stmt = $wpdb->prepare("SELECT * FROM {$media_table} WHERE playlist_id = %d", $playlist_id);
        $result = $wpdb->get_results($stmt, ARRAY_A);

    foreach($result as $row){

        $trimmed_array = array_map('trim',array_values($row));
        $line = str_replace('^', '', $trimmed_array);
        fputcsv($fp, $line, '|','^');

    }

    // return to the start of the stream
    rewind($fp);

    // add the in-memory file to the archive, giving a name
    $zip->addFromString($table.'.csv', stream_get_contents($fp) );

    //close the file
    fclose($fp);

    $zip->close();

    echo json_encode(array('zip' => $zipname));

    wp_die();

}

0 个答案:

没有答案