将带有消息的文本文件写入FTP

时间:2015-04-02 16:31:06

标签: php ftp

我想创建一个文件夹,并在FTP服务器上的该文件夹中创建一个带有给定消息的文件。 以下是我的尝试:

<?php

$dirname = "files/";
$dir = $_GET["name"];
$dirname .= $dir;
$filepath = $dirname."/message.txt";
$txt = $_GET["message"];

// set up basic connection
$conn_id = ftp_connect("example.com");

// login with username and password
$login_result = ftp_login($conn_id, "login", "password");

// try to create the directory and file
if (ftp_mkdir($conn_id, $dirname)) {
 echo "successfully created $dirname\n";
 $myfile = fopen('php://temp', 'r+') or die("Unable to open file!");
 fwrite($myfile, $txt);
 rewind($myfile);
 ftp_fput($conn_id, $filepath, $myfile, FTP_ASCII);

} else {
 echo "There was a problem while creating $dirname\n";
}

// close the connection
ftp_close($conn_id);
?>

这将创建具有给定名称的文件夹,并将message.txt文件放在该文件夹中,但该文件始终为空。如何将我的消息添加到文件中?

2 个答案:

答案 0 :(得分:2)

我最习惯使用shell_exec写入本地文件。我的解决方案看起来像这样。

<?php

$dirname = "files/";
$dir = $_GET["name"];
$dirname .= $dir;
$filepath = $dirname."/message.txt";
$txt = $_GET["message"];

// set up basic connection
$conn_id = ftp_connect("example.com");

// login with username and password
$login_result = ftp_login($conn_id, "login", "password");

// try to create the directory and file
if (ftp_mkdir($conn_id, $dirname)) {
echo "successfully created $dirname\n";
$myfile = fopen('php://temp', 'r+') or die("Unable to open file!");

// Here is the good stuff with shell_exec.
$myfilelocation = '~/myfile.txt';
shell_exec( "cat $txt >> $myfilelocation" );

ftp_fput($conn_id, $filepath, $myfile, FTP_ASCII);

} else {
echo "There was a problem while creating $dirname\n";
}

// close the connection
ftp_close($conn_id);
?>

答案 1 :(得分:0)

您好像以阅读模式('php://temp', 'r+')

打开文件

尝试fopen ('php://temp', 'w +')