使用php从远程服务器(SFTP)下载sqlite数据库

时间:2014-01-14 16:14:32

标签: php sftp

我目前正在开发一个项目,我需要将sqlite数据库下载到本地文件夹。那么是否可以从网络服务器下载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);
}

2 个答案:

答案 0 :(得分:1)

php核心中默认不安装

ssh_*函数。 你必须使用pecl添加它们,请参阅php手册以获得一个很好的描述:http://de1.php.net/manual/en/ssh2.installation.php

答案 1 :(得分:0)

我认为您可以更轻松地使用phpseclib, a pure PHP SFTP implementation。它不仅可以提供比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);
}