Generate CSV file on an external FTP server in PHP

2020-02-12 16:53发布

问题:

I have some PHP code that successfully exports a MySQL table to a CSV file.

I would like to add to that code, so instead of saving locally the CSL file is exported to/saved on an external FTP server.

My current code:

//open database connection                            
require ('../database-config.php');

//name the file
header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=exported-data.csv');

//SQL Query for Data
$sql = "SELECT * FROM data;";        
//Prepare Query, Bind Parameters, Excute Query
$STH = $dbh->prepare($sql);
$STH->execute();

//Export to .CSV
$fp = fopen('php://output', 'w');

$first_row = $STH->fetch(PDO::FETCH_ASSOC);
$headers = array_keys($first_row);

fputcsv($fp, $headers); // put the headers
fputcsv($fp, array_values($first_row)); // put the first row

while ($row = $STH->fetch(PDO::FETCH_NUM))  {
fputcsv($fp,$row); // push the rest
}
fclose($fp);

I know I'll need to add some new variables;

$ftp_server="ftp.remotersite.com";
$ftp_path="/path/to/somefile";
$ftp_username="username";
$ftp_userpass="password";

But, I'm not sure the best way to use ftp_put (or should it be ftp_fput?) to transfer to the external destination.

Thanks in advance.

回答1:

If you have ftp:// URL wrappers enabled, just open the file directly on FTP server:

$fp = fopen('ftp://username:password@ftp.example.com/path/to/somefile', 'w');

If you do not have the wrapers enabled, see:
Creating and uploading a file in PHP to an FTP server without saving locally