Home » Php » ftp – fopen (php) from remote server works only for reading

ftp – fopen (php) from remote server works only for reading

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to open a text file from a remote server and to write some information in it, using PHP fopen().

allow_url_fopen is ON (in my php.ini).

I can read this remote file, but can’t write in it.

Code:

<?php
$data = 'some text';
$filename = 'ftp://admin:[email protected]/web/domain.com/public_html/test2.txt';
$fh = fopen($filename, 'r'); 
echo fread($fh, filesize($filename));
fclose($fh);

$fh = fopen($filename, 'w+'); 
if ($fh) {
  echo 'remote file is opened, writing data';
  fwrite($fh, $data);
  fclose($fh);
} else {
  echo 'remote file not opened';
}
?>

Shows:
some text
remote file not opened

What can i do make in write to file?

How to&Answers:

From PHP: ftp://

Allows read access to existing files and creation of new files via FTP.

You can open files for either reading or writing, but not both simultaneously. If the remote file already exists on the ftp server and you attempt to open it for writing but have not specified the context option overwrite, the connection will fail. If you need to overwrite existing files over ftp, specify the overwrite option in the context and open the file for writing. Alternatively, you can use the FTP extension.

Also a note:

Note: Appending

Files may be appended via the ftp:// URL wrapper.

I’m not sure if overwrite means truncate or not. If so, you can download, modify and then upload and overwrite or look at PHP: FTP Functions.

More from PHP: Using remote files:

You can only create new files using this method; if you try to overwrite a file that already exists, the fopen() call will fail.

And then a note:

Note:

You might get the idea from the example above that you can use this technique to write to a remote log file. Unfortunately that would not work because the fopen() call will fail if the remote file already exists. To do distributed logging like that, you should take a look at syslog().

So it seems that you can create a file or completely overwrite an existing one. I haven’t seen an example for append.

Answer:

PHP FTP URL wrapper does not support opening the file simultaneously for reading and writing. So you cannot use w+ mode (reading and writing). Use w mode (writing only).

Additionally, FTP URL wrapper does not allow overwriting of an existing file by default, you need to enable it using overwrite FTP context option.

$context = stream_context_create(['ftp' => ['overwrite' => true]]);
$fh = fopen($filename, 'w', false, $context); 

Though this will be all quite inefficient, as you will be opening whole FTP session twice. Once for reading and once for writing. You better use FTP functions ftp_get and ftp_put over one session.