0

I have a PHP file which generates a CSV file using the code below:

$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;

I've not included the code which creates the content as it does it's job fine. What I need to do is use terminal to run this file and upload the results to an sftp server. I can connect to the server fine in terminal.

I have been using the php command in terminal to produce the resulting CSV. This however doesn't produce the CSV like it does when run in the browser. What it does do is produce the CSV as a string.

Is there a way to either produce the CSV as a file like the browser so I can grab it in terminal and upload it to the SFTP server? Alternatively is it possible to echo out the string produced from the PHP file and create the CSV myself using this kind of command:

echo "boo,to,you">file.csv
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
jampez77
  • 5,012
  • 7
  • 32
  • 52

1 Answers1

0

Just redirect the php output to a temporary file and upload the file.

php yourscript.php > /tmp/file.csv
echo "put /tmp/file.csv" | sftp user@example.com

If you want to do it without the temporary file, you cannot do with just the (OpenSSH) sftp as it cannot read contents to upload from the stdin. Neither the (OpenSSH) scp can.


You can of course produce the file from PHP code itself, if that suits your task better.

Just use the file_put_contents():

file_put_contents("/tmp/file.csv", $csv_output);

See How to write into a file in PHP?


The suggestion by @MarcB should work, if the remote server is *nix (understands the cat) and allows a shell access.

php yourscript.php | ssh user@example.com 'cat > file.csv'

Though obviously that's not "SFTP upload" anymore.


When producing a file, do not use the the header(). Headers make sense in webserver environment only, not when you use the PHP as a scripting language in a shell.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
  • sorry this response has taken a while. using your code results in exec request failed on channel 0. if i change ssh to sftp it will prompt login and then respond with remote open("/file.csv"): Permission denied, is that a server issue? – jampez77 Dec 18 '14 at 10:32
  • `ssh`: You need shell access to that approach. Do you? `sftp`: Is your account is chrooted? If it is not, `/file.csv` is a path to a root folder, that you won't have a write access to, unless you login with `root`. Possibly you need to use full path to the file, like `/home/user/file.csv`? – Martin Prikryl Dec 18 '14 at 12:50