Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

155
Views
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()]);
}
about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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

about 4 years ago · Santiago Trujillo Report

0

I've figured out myself...

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

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

about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!