2

I'm trying to updating a CSV file which in a external FTP server, I tried to follow the basic ftp_fput() but it's not working. File is not updating and also a blank CSV file is downloading when I run this script which is not needed. I've been trying to solve this but can't find the solution

<?php

// connect and login to FTP server
//ftp setup
 $ftp_server = "ftp.test.test.co.uk";
        $ftp_conn = ftp_connect($ftp_server) or die("Could not connect to $ftp_server");
        $ftp_username='ftp_username';
        $ftp_userpass='ftp_userpass';
      $login = ftp_login($ftp_conn, $ftp_username, $ftp_userpass);

//local DB setup
$servername = "localhost";
$username = "root";
$password = "TEST";
$dbname= "TEST";

// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
//END database connection//



$sql = "SELECT sku,SUM(quantity) as quantity FROM tbl_old_books GROUP BY isbn";

$result = $conn->query($sql);

         header("Content-Disposition: attachment; filename=AllOpenOrders.csv");
         header("Content-Type: application/csv; ");

         // file creation
       $file = fopen('php://temp', 'W');

        $header = array("SKU","QUANTITY");
        fputcsv($file, $header);


      if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
            fputcsv($file, $row );
        }
    }

 $remote_path = "/export/AllOpenOrders.csv";

ftp_fput($ftp_conn, $remote_path, $file, FTP_BINARY, 0);


  fclose($file);
ftp_close($ftp_conn);
?>

1 Answers1

1

You file handler $file points at the end of the file as you write in it. There is nothing left to write via ftp_fput.

You can reset your file pointer at the beginning of the file with rewind($file); before writing in the FTP : rewind documentation

Joffrey Schmitz
  • 2,393
  • 3
  • 19
  • 28