Deniss Muntjans
Deniss Muntjans

Reputation: 379

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

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()]);
}

Upvotes: 9

Views: 1635

Answers (4)

Gaurav
Gaurav

Reputation: 713

I have changed your code check it:

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();

    ob_start();
    $fp = fopen('path/to/folder/filename.csv', 'w');
    foreach ($data as $row) {

        if ( ! fputcsv($fp, $row))
        {
            show_error("Can't write line $n: $line");
        }
    }
    fclose($fp) or show_error("Can't close path/to/folder/filename.csv");
    $str = ob_get_contents();
    ob_end_clean();
    print "\xEF\xBB\xBF"; // UTF-8 BOM
    print $str;
}
catch(PDOException $e){
    echo json_encode((object)['error'=>true,'message'=>$e->getMessage()]);
}

Also csv folder should have permission for write and read.

Upvotes: 2

Deniss Muntjans
Deniss Muntjans

Reputation: 379

I've figured out myself...

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

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

Upvotes: 5

Kai Adelmann
Kai Adelmann

Reputation: 199

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

Upvotes: 5

Jose Marques
Jose Marques

Reputation: 748

A simple way make a file upload to your server. To do it automatically is a bit harder, but there's nothing like trying. For that you need to know a little of AJAX, Json, JQuery and file upload.

A normal file upload you need in your client:

<!DOCTYPE html>
<html>
<body>

<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>

</body>
</html>

In your server:

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

In your case you don't want to create a interface that get the file to the server. For that you need to use some ajax and json or Jquery File Upload.

Look on the site for exemples.

I have tried to do something like that but I got stuck in ajax posting, It worked but only within a form. The way around it's to send only the file to the server.

when you create the first code and the first problems appear I whill try to help . Two heads work better than one.

Upvotes: 3

Related Questions