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

时间:2014-01-29 14:09:21

标签: php file ftp

尝试使用fopen选项a现有文件时,我收到此错误:

  

警告: fopen(ftp://...@sub.mysite.com/var/www/diversos/01_2014.txt)   [function.fopen]:无法打开流: FTP服务器报告451   /var/www/diversos/01_2014.txt:不允许追加/重启,试试   再次在/ strong/html/prod/my_transfer_file.php 150

my_transfer_file.php - 第150行

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

是FTP还是代码问题?我该怎么做才能解决这个问题? 之前从未见过这个错误。

2 个答案:

答案 0 :(得分:6)

这意味着另一端的FTP服务器不支持向文件追加数据。由于这是服务器级别的配置,除非您具有对服务器的管理访问权限以更改设置,否则您实际上无法对其进行任何操作。

我唯一能建议的是下载完整文件,在本地附加,删除遥控器然后上传附加文件。您可以使用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);
}

答案 1 :(得分:1)

在fopen中使用'a'选项时,我的服务器给了我相同的信息。 'a'选项将文件指针放在文件的末尾,这意味着任何写入都将在数据前添加而不是覆盖文件。使用'w'选项检查它是否有效,例如

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

如果您需要前置,请先读取文件,然后在本地将新内容添加到文件末尾。

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

在我的服务器上,我必须打开两次流,因为它不允许它以读/写模式打开(选项'wr'或'w +')

您也可以尝试使用file_get_contents和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);