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

时间:2015-05-29 11:38:33

标签: php debian vpn file-transfer

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

我提到了shell_execscp,如上所述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连接的机器。

1 个答案:

答案 0 :(得分:2)

我安装了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。