php FTP包装写入空文件(0字节),FTP扩展不';t


php FTP Wrapper writes empty files (0 Byte), FTP Extension doesn't

在运行PHP 5.2.17的服务器上,使用任何使用内置ftp包装器上传文件的函数,在服务器上创建一个空文件:

  • file_put_contents()返回准确的字节数
  • copy()也返回true

两者都创建了文件,但它是空的。

当尝试从FTP扩展使用ftp_put()时,无论是在二进制模式还是ascii模式下,它都能很好地工作。

在我的PHP 5.3.10工作站上,它也可以与包装器配合使用。

代码中:

$source = '/tmp/testfile';
$target = 'ftp://user:pass@example.com/testfile';
copy($source, $target);

不会给出任何错误或警告,但会在服务器上留下一个空文件。

$source = '/tmp/testfile';
$target = 'testfile';
$ftp = ftp_connect('example.com');
ftp_login($ftp, 'user', 'pass');
ftp_put($ftp, $target, $source, FTP_ASCII);
ftp_close($ftp);

在各个方面都有效。

谢谢你的建议!

您尝试过SSH2库吗?下面的一些示例实现:

public function uploadSFTP($host_name, $port, $user, $publicSshKeyPath, $privateSshKeyPath, $remoteFile, $localFile, $fileOperation = 'w') 
{
    $ssh_conn = ssh2_connect($host_name, $port);
    if (ssh2_auth_pubkey_file($ssh_conn, $user, $publicSshKeyPath, $privateSshKeyPath)) 
    {
        $sftp_conn = ssh2_sftp($ssh_conn);
        $inputfileStream = @fopen('ssh2.sftp://' . $sftp_conn . $remoteFile, $fileOperation);
        try 
        {
            if (!$inputfileStream)
                throw new Exception('Could open remote file for writing: ' . $remoteFile);
            $localFileContents = @file_get_contents($localFile);
            if ($localFileContents === FALSE)
                throw new Exception('Could not open local file for reading :' . $localFile);
            if (@fwrite($inputfileStream, $localFileContents) === FALSE)
                throw new Exception('Could not SFTP file');
        } 
        catch (Exception $e) 
        {
            // Do something...
        }
        fclose($sftpInfileStream);
    }
}