PHP FTP错误:451 - 不允许附加/重新启动

When trying to fopen an existent file with a option, I'm receiving this error:

Warning: fopen(ftp://...@sub.mysite.com/var/www/diversos/01_2014.txt) [function.fopen]: failed to open stream: FTP server reports 451 /var/www/diversos/01_2014.txt: Append/Restart not permitted, try again in /www/html/prod/my_transfer_file.php on line 150

my_transfer_file.php - Line 150

fopen ('ftp://user:pass@sub.mysite.com/var/www/diversos/01_2014.txt', "a" );

Is it a FTP or code issue? What do I do to solve this problem? Never saw this error before.

It means the FTP server on the other end doesn't support appending data to files. Since this is a server level configuration, unless you have administrative access to the server to change the setting, you really can't do anything about it.

The only thing I could suggest is to download the full file, append it locally, delete the remote and then upload the appended file. You could do this by using the PHP FTP library

$ftp = ftp_connect('yourserver.com');
$local = 'localfile.txt';
$remote = 'remote.txt';
if(ftp_login($ftp, 'username', 'password')){
    ftp_get($ftp, $local, $remote);
    $file = fopen($local, 'a');
    fwrite($file, 'your data here');
    fclose($file);
    ftp_delete($ftp, $remote);
    ftp_put($ftp, $remote, $local, FTP_ASCII); // It's a text file so it will be ASCII
    ftp_close($ftp);
}

My server gives me the same message when using the 'a' option in fopen. The 'a' option puts the file pointer at the end of the file, meaning any write will prepend the data rather than overwrite the file. check if it will work using just the 'w' option, such as

fopen ('ftp://user:pass@sub.mysite.com/var/www/diversos/01_2014.txt', "w" );

If you need to prepend, read the file first and than add the new contents to the end of the file locally.

$file ="ftp://user:pass@domain.com/file.ext";
$stream  = fopen($file, 'r');

$contents = fread($stream, 1024);

// since your likely not just reading it for fun
$contents = do_something_to_contents($contents);

$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);

$stream  = fopen($file, 'w', false, $context);

fwrite($stream, $contents);

On my server I had to open the stream twice because it wouldn’t allow it to open in read/write mode (option 'wr' or 'w+')

You can also try using file_get_contents and file_put_contents

// the file your trying to get
$file ="ftp://user:pass@domain.com/file.ext";

// get the file
$contents = file_get_contents($file);

// write
$opts = array('ftp' => array('overwrite' => true));
$context = stream_context_create($opts);
file_put_contents($file, $contents, NULL, $context);