testus
testus

Reputation: 183

Writte text file with message to FTP

I want to create a folder and create a file with a given message inside that folder on a FTP server. Following is my attempt:

<?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);
?>

This creates the folder with the given name and also puts a message.txt file inside that folder but the file is always empty. How can I add my message to the file?

Upvotes: 0

Views: 92

Answers (2)

anEffingChamp
anEffingChamp

Reputation: 166

I would be most comfortable with using shell_exec to write to a local file. My solution would look like this.

<?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);
?>

Upvotes: 2

You seem to be opening the file in read mode ('php://temp', 'r+')

try fopen ('php://temp', 'w +')

Upvotes: 0

Related Questions