Page 1 of 1

get_file_contents, fopen & fwrite via ftp_connect

Posted: Tue Sep 07, 2010 4:04 am
by dameunmate
I'm trying to create an online web editor. It works fine for opening and writing files on the same server where the web editor is hosted, but I want it to be able to get_file_contents, fopen and fwrite files on a remote server, logging in with ftp_connect and ftp_login. I've noticed the functions ftp_get and ftp_fget but I'd rather not create another local file, if possible I want to open the remote file directly into a <texarea> then save it directly back to the remote server. Is this possible? So far I just get errors...

Here's an example of the code I'm trying to combine, to retrieve the contents of a file on a remote server and put them in a <textarea>:

Code: Select all

<?php

    $conn = ftp_connect("ftp.domain.com");
    ftp_login($conn, "username", "password");
    ftp_pasv($conn, true);

  $filename='example.php';

// open file 
  $fh = fopen($filename, "r") or die("Could not open file!"); 

// read file contents
  $datax = fread($fh, filesize($filename)) or die("Could not read file!");
  $data=htmlspecialchars($datax);

// close file
  fclose($fh);

// close this connection
  ftp_close($conn);

echo '<textarea cols="200%" rows="50">'.$data.'</textarea>';

?>
And another failed example:

Code: Select all

<?php

  $filename='editor.php';

  $fh = fopen("ftp://username:password@domain.com/example.php", "r") or die("Could not open file!"); 

  $datax = fread($fh, filesize($filename)) or die("Could not read file!");
  $data=htmlspecialchars($datax);

  fclose($fh);

echo '<textarea cols="200%" rows="50">'.$data.'</textarea>';

?>

Re: get_file_contents, fopen & fwrite via ftp_connect

Posted: Tue Sep 07, 2010 9:00 am
by requinix
No, it isn't. Create a temporary file, write to it, upload it, and delete it.

tmpfile and ftp_fput are your friends. Don't forget to seek to the beginning of the file between writing and uploading.