[英]Download sqlite database from remote server(SFTP) using php
我目前正在一個需要將sqlite數據庫下載到本地文件夾的項目中,因此可以從Web服務器下載SQLite數據庫,然后在數據庫中搜索內容嗎? 我對php很陌生,但我到了這一點,並陷入了這個錯誤。
致命錯誤:調用未定義函數ssh2_connect()
<?php
$host = '11.11.11.2';
$port = 2222;
$username = 'root';
$password = 'sdfsdf';
$remoteDir = '/home/root/systools/WM/WebMobility.db';
$localDir = '/c:/explode';
if (!function_exists("ssh2_connect"))
die('Function ssh2_connect not found, you cannot use ssh2 here');
if (!$connection = ssh2_connect($host, $port))
die('Unable to connect');
if (!ssh2_auth_password($connection, $username, $password))
die('Unable to authenticate.');
if (!$stream = ssh2_sftp($connection))
die('Unable to create a stream.');
if (!$dir = opendir("ssh2.sftp://{$stream}{$remoteDir}"))
die('Could not open the directory');
$files = array();
while (false !== ($file = readdir($dir)))
{
if ($file == "." || $file == "..")
continue;
$files[] = $file;
}
foreach ($files as $file)
{
echo "Copying file: $file\n";
if (!$remote = @fopen("ssh2.sftp://{$sftp}/{$remoteDir}{$file}", 'r'))
{
echo "Unable to open remote file: $file\n";
continue;
}
if (!$local = @fopen($localDir . $file, 'w'))
{
echo "Unable to create local file: $file\n";
continue;
}
$read = 0;
$filesize = filesize("ssh2.sftp://{$sftp}/{$remoteDir}{$file}");
while ($read < $filesize && ($buffer = fread($remote, $filesize - $read)))
{
$read += strlen($buffer);
if (fwrite($local, $buffer) === FALSE)
{
echo "Unable to write to local file: $file\n";
break;
}
}
fclose($local);
fclose($remote);
}
ssh_*
函數不是默認安裝在php core中。 您必須使用pecl來添加它們,請參見php手冊以獲取詳細說明: http ://de1.php.net/manual/zh/ssh2.installation.php
我認為使用純PHP SFTP實現phpseclib會更輕松。 與libssh2相比,它不僅使代碼更易於移植,更易於部署,而且代碼也更短:
<?php
$host = '11.11.11.2';
$port = 2222;
$username = 'root';
$password = 'sdfsdf';
$remoteDir = '/home/root/systools/WM/WebMobility.db';
$localDir = '/c:/explode';
include('Net/SFTP.php');
$sftp = new Net_SFTP($host, $port);
if (!$sftp->login($username, $password))
die('Unable to authenticate.');
$files = $sftp->nlist($remoteDir);
foreach ($files as $file) {
if ($file == "." || $file == "..")
continue;
$sftp->get($remoteDir . '/' . $file, $localDir . $file);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.