我的 php 网站托管在 Debain 机器中,我想将文件从该机器移动到通过 VPN 连接的另一台 Debain。
我试过shell_exec和 scp ,如前所述here .
<?php
$output = shell_exec('scp file1.txt <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f2e0f7f2f3e4d6f2f3f7e2fee5e2f7e4b8f5f9fb" rel="noreferrer noopener nofollow">[email protected]</a>: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。
关于php - 使用 php 在两个 Debian 服务器之间复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30528647/