简体   繁体   English

通过终端将PHP生成的CSV文件上传到SFTP服务器

[英]Uploading a PHP generated CSV file to SFTP server via terminal

I have a PHP file which generates a CSV file using the code below: 我有一个PHP文件,该文件使用以下代码生成CSV文件:

$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. 我需要做的是使用终端运行该文件,并将结果上传到sftp服务器。 I can connect to the server fine in terminal. 我可以在终端中很好地连接到服务器。

I have been using the php command in terminal to produce the resulting CSV. 我一直在终端中使用php命令来生成结果CSV。 This however doesn't produce the CSV like it does when run in the browser. 但是,它不会像在浏览器中运行时那样生成CSV。 What it does do is produce the CSV as a string. 它所做的是将CSV生成为字符串。

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? 有没有办法像浏览器一样将CSV生成为文件,以便我可以在终端中抓取并将其上传到SFTP服务器? Alternatively is it possible to echo out the string produced from the PHP file and create the CSV myself using this kind of command: 另外,也可以使用以下命令回显从PHP文件生成的字符串并自己创建CSV:

echo "boo,to,you">file.csv

Just redirect the php output to a temporary file and upload the file. 只需将php输出重定向到一个临时文件并上传该文件。

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. 如果要在没有临时文件的情况下执行此操作,则不能仅使用(OpenSSH) sftp因为它无法读取要从stdin上传的内容。 Neither the (OpenSSH) scp can. (OpenSSH) scp都不能。


You can of course produce the file from PHP code itself, if that suits your task better. 当然,如果更适合您的任务,则可以从PHP代码本身生成文件。

Just use the file_put_contents() : 只需使用file_put_contents()

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

See How to write into a file in PHP? 请参阅如何用PHP写入文件?


The suggestion by @MarcB should work, if the remote server is *nix (understands the cat ) and allows a shell access. 如果远程服务器是* nix(理解cat )并允许外壳程序访问,则@MarcB的建议应该起作用。

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

Though obviously that's not "SFTP upload" anymore. 虽然显然不再是“ SFTP上传”了。


When producing a file, do not use the the header() . 生成文件时,请勿使用header() Headers make sense in webserver environment only, not when you use the PHP as a scripting language in a shell. 标头仅在Web服务器环境中有意义,而在将PHP用作Shell中的脚本语言时则没有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM