How to Sftp With PHP

connect to a server via sftp php

You might have an easier time using phpseclib, a pure PHP SFTP client. Here's an example:

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}

echo $sftp->pwd() . "\r\n";
$sftp->put('filename.ext', 'hello, world!');
print_r($sftp->nlist());
?>

The problem with libssh2, as everyone's recommending, is that it's not very widely deployed, it's API isn't exactly the most reliable, it's unreliable, poorly supported, etc.

Uploading files with SFTP

With the method above (involving sftp) you can use stream_copy_to_stream:

$resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
$srcFile = fopen("/home/myusername/".$csv_filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);

You can also try using ssh2_scp_send

How to SFTP upload files from PHP

http://phpseclib.sourceforge.net/documentation/intro.html#intro_usage_correct

Per that, phpseclib's root directory needs to be in your include_path. From that page:

<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');

include('Net/SFTP.php');
?>

You should really familiarize yourself with this kind of include technique - it's pretty standard for PEAR libraries and Zend ones.

PHP download from remote server via sftp

Here is a small code on how to read the folder and download all its files:

<?php
$host = 'localhost';
$port = 22;
$username = 'username';
$password = 'password';
$remoteDir = '/must/be/the/complete/folder/path';
$localDir = '/can/be/the/relative/or/absolute/local/path';

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://{$stream}/{$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://{$stream}/{$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);
}

You can also resume this code to (it will not copy directories):

while (false !== ($file = readdir($dirHandle)))
{
if ($file == "." || $file == "..")
continue;

echo "Copying file: $file\n";
if(!ssh2_scp_recv($connection, $remoteDir . $file, $localDir . $file))
echo "Could not download: ", $remoteDir, $file, "\n";
}

If you do not use the full path on the remote folder it will not work:

opendir("ssh2.sftp://{$stream}{$remoteDir}")

How I can move file on a SFTP server in PHP

Use ssh2_sftp_rename:

ssh2_sftp_rename($sftp, $path_from, $path_to);

Assuming both variables contain full paths to files, e.g. like:

$path_from = "/source/directory/myfile.txt";
$path_to = "/destination/directory/myfile.txt";

SFTP from within PHP

Yes, you can do that with cURL. To switch from FTP to SFTP all you have to do is to change protocol option form CURLPROTO_FTP to CURLPROTO_SFTP.

cURL supports following protocols: HTTP, HTTPS , FTP, FTPS, SCP, SFTP, TELNET, LDAP, LDAPS, DICT, FILE, TFTP.

BTW. SFTP is not to be confused with FTPS. SFTP is SSH File Transfer Protocol, while FTPS is FTP over SSL.

How to transfer a file to the server using sftp?

If you just want to transmit a file and don't care about using scp or sftp, then I would encourage you to use scp. Here comes a basic example (taken from the PHP manual):

$connection = ssh2_connect('www.example.com', 22);
if($connection === FALSE) {
die('Failed to connect');
}

$state = ssh2_auth_password($connection, 'username', 'password');
if($state === FALSE) {
die('Failed to authenticate');
}

$state = ssh2_scp_send($connection, '/local/filename', '/remote/filename', 0644);
if($state === FALSE) {
die('Failed to transfer the file');
}


Related Topics



Leave a reply



Submit