使用 php 在两个 Debian 服务器之间复制文件

Copying files between two Debian Servers using php

我的 php 网站托管在 Debain 机器上,我想将文件从该机器移动到另一个通过 VPN 连接的 Debain。

我试过了shell_exec and scp , as mentioned here

<?php
    $output = shell_exec('scp file1.txt dvader@deathstar.com:somedir');
    echo "<pre>$output</pre>";
?>

我也试过使用 SFTP

<?php

class SFTPConnection
{
    private $connection;
    private $sftp;

    public function __construct($host, $port=22)
    {
        $this->connection = @ssh2_connect($host, $port);
        if (! $this->connection)
            throw new Exception("Could not connect to $host on port $port.");
    }

    public function login($username, $password)
    {
        if (! @ssh2_auth_password($this->connection, $username, $password))
            throw new Exception("Could not authenticate with username $username " .
                                "and password $password.");

        $this->sftp = @ssh2_sftp($this->connection);
        if (! $this->sftp)
            throw new Exception("Could not initialize SFTP subsystem.");
    }

    public function uploadFile($local_file, $remote_file)
    {
        $sftp = $this->sftp;
        $stream = @fopen("ssh2.sftp://$sftp$remote_file", 'w');

        if (! $stream)
            throw new Exception("Could not open file: $remote_file");

        $data_to_send = @file_get_contents($local_file);
        if ($data_to_send === false)
            throw new Exception("Could not open local file: $local_file.");

        if (@fwrite($stream, $data_to_send) === false)
            throw new Exception("Could not send data from file: $local_file.");

        @fclose($stream);
    }
}

try
{
    $sftp = new SFTPConnection("localhost", 22);
    $sftp->login("username", "password");
    $sftp->uploadFile("/tmp/to_be_sent", "/tmp/to_be_received");
}
catch (Exception $e)
{
    echo $e->getMessage() . "\n";
}

?>

简单地说,我的问题是我无法将文件从我的 php 应用程序正在运行的一台机器移动到另一台通过 VPN 连接的机器。

我安装了 proftpd 并创建了一个用户,如前所述 here

请注意默认端口为 21。并确保重新启动 proftpd:

service proftpd restart

我用来上传文件的代码是:

index.php

<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$file = 'a.txt';
$remote_file = 'b.txt';
$conn_id = ftp_connect('www.xxx.com',21);
$login_result = ftp_login($conn_id, "username","password");
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
 echo "successfully uploaded $file\n";
} else {
 echo "There was a problem while uploading $file\n";
 die();
}
ftp_close($conn_id);
?>

此处 a.txt 与 index.php 在同一目录中。

它将文件复制到您提到的文件夹,供特定用户访问并命名为 b.txt。