Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate CSV, download to local machine and save to the server at the same time

Tags:

php

download

I've got this PHP script (see below) which allows me to generate CSV file using SQL query and download it to my local machine but how can I save it to remote server (http://myserverblabla.com/uploads) at the same time to keep a backup copy over there? Would it be possible to modify my existing script to achieve that?

include 'class/database.class.php';

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"filename.csv\";" );
header("Content-Transfer-Encoding: binary");

$database = new Database();

try{
    // Select query
    $database->query("SOME SQL QUERY");
    $data = $database->resultset();

    $fp = fopen('php://temp', 'r+');
    foreach ($data as $row) {
        if (! isset($ch)) {
            foreach ($row as $header => $value) {
                if (isset($ch))
                    $ch .= ",";
                    else
                        $ch = "";

                        $ch .= '"' . addslashes($header) . '"';
            }
        }
        fputcsv($fp, $row, ",", '"');
    }

    rewind($fp);
    $csv = fread($fp, 1048576);
    fclose($fp);
    echo $ch . PHP_EOL .  rtrim($csv, PHP_EOL);
}
catch(PDOException $e){
    echo json_encode((object)['error'=>true,'message'=>$e->getMessage()]);
}
like image 659
Deniss Muntjans Avatar asked Apr 04 '17 08:04

Deniss Muntjans


2 Answers

Why not simply copying the file you generate? Just insert something like copy(your file $fp, destination dir/filename); after your fclose($fp);

like image 64
Kai Adelmann Avatar answered Sep 26 '22 22:09

Kai Adelmann


I've figured out myself...

I've changed fopenfunction in order to save CSV file into server:

$fp = fopen('uploads/test.csv', 'w+');

like image 29
Deniss Muntjans Avatar answered Sep 23 '22 22:09

Deniss Muntjans