Separate PHP processes using same ssh2.sftp resource - php

I am using the PECL ssh2 module to output XML data to a sftp server. I have two entirely separate PHP scripts which gather different data and send the output to different file on the stfp server.
CUSTOMER EXPORT:
$conn = ssh2_connect(SFTP_SERVER, SFTP_PORT);
ssh2_auth_password($conn, SFTP_USER, SFTP_PWD);
$sftp = ssh2_sftp($conn);
$file = 'ssh2.sftp://' . $sftp . CUSTOMER_EXPORT_PATH . CUSTOMER_EXPORT_FILENAME;
$doc = new DOMDocument('1.0','UTF-8');
CustomerExportXML($doc);
if (file_exists($file)) {
unlink($file);
}
$bytes_saved = $doc->save($file);
PRODUCT EXPORT:
$conn = ssh2_connect(SFTP_SERVER, SFTP_PORT);
ssh2_auth_password($conn, SFTP_USER, SFTP_PWD);
$sftp = ssh2_sftp($conn);
$file = 'ssh2.sftp://' . $sftp . PRODUCT_EXPORT_PATH . PRODUCT_EXPORT_FILENAME;
$doc = new DOMDocument('1.0','UTF-8');
ProductExportXML($doc);
if (file_exists($file)) {
unlink($file);
}
$bytes_saved = $doc->save($file);
In each case the XxxExportXML($doc) function takes a couple of minutes to gather the relevant data and stuff it in to $doc.
Each script works as is and exports the correct data to the correct place.
The problem is when their execution overlaps only the last one executed actually writes to the sftp server. If I echo out the $file variable then in each case they both have the same resource ID ie ssh2.sftp://ResourceID#150/Customer/Customer.xml and ssh2.sftp://ResourceID#150/Product/Product.xml
So my question is why are these two processes interfering with each other and how do I fix it so they can both be run at the same time?

So they're two different scripts? That's... weird. Maybe try phpseclib, a pure PHP SFTP implementation, instead. eg.
<?php
include('Net/SFTP.php');
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');

Related

Listing files on remote host failed

I have a code:
scandir("ssh2.sftp://" . intval($sftpHandle) . $remoteDir);
Why the same code works for one server but doesn't for another?
There is a files on both servers. I can manage them via Filezilla without problems.
The first one just returns array('.') even if there is a lot of files, another one returns array('file1', 'file2', 'file3', etc)
Even if I cannot list a files using scandir(), command ssh2_scp_recv($sshHandle, $remoteDir/file1, $localDir/file1) works fine.
Also ssh2_exec($sshHandle, "ls $remoteDir") works fine to me.
Please note that I'm using $ftpHandle for scandir() but $sshHandle for ssh2_* functions.
Using $sshHandle for scandir() cause "Segmentation fault" error.
I know that I can workaround this by parsing ssh2_exec($sshHandle, "ls $remoteDir") output, but would prefer do it right way if possible.
My PHP version is 7.0.31
This should work probably
$connection = ssh2_connect($url);
// login
if (!ssh2_auth_password($connection, $username, $password)) throw new Exception('Unable to connect server.');
// Create SFTP resource
if (!$sftp = ssh2_sftp($connection)) throw new Exception('Unable to create connection.');
$localDir = '/path/to/local/dir';
$remoteDir = '/path/to/remote/dir';
// download all the files or list all
$files = scandir('ssh2.sftp://' . $sftp . $remoteDir);
if (!empty($files)) {
foreach ($files as $file) {
if ($file != '.' && $file != '..') {
// here you can print files using $file
// or download file by uncommenting below line
//ssh2_scp_recv($connection, "$remoteDir/$file", "$localDir/$file");
}
}
}

How to Copy one folder local file to SFTP server using PHP

This is my code to send single file from local to SFTP server. Single file successfully send.
I want to send one folder from local to SFTP server , but i dont know how to send one folder. i need help
<?php
$src = 'xxxxxxx';
$filename = 'test.txt';
$dest = 'xxxxxxxx'.$filename;
// set up sftp ssh-sftp connection
$connection = ssh2_connect('xxxxxx', 22);
ssh2_auth_password($connection, 'username', 'password');
// Create SFTP session
$sftp = ssh2_sftp($connection);
$sftpStream = #fopen('ssh2.sftp://'.$sftp.$dest, 'w');
try {
if (!$sftpStream) {
throw new Exception("Could not open remote file: $dest");
}
$data_to_send = #file_get_contents($src);
if ($data_to_send === false) {
throw new Exception("Could not open local file: $src.");
}
if (#fwrite($sftpStream, $data_to_send) === false) {
throw new Exception("Could not send data from file: $src.");
} else {
//Upload was successful, post-upload actions go here...
}
fclose($sftpStream);
} catch (Exception $e) {
error_log('Exception: ' . $e->getMessage());
fclose($sftpStream);
}
?>
ssh2_scp_send in php looks like just support sending file.
maybe these ways work:
1.compress folder, send the compressed file
2.use ssh2 to mkdir, then send each file iteratively
3.try with system() function to excute cmd line order "scp -r folder_path user#host:target_path"

PHP SFTP Simple File Upload

I'm using phpseclib - SFTP class and am trying to upload a file like so -
$sftp = new Net_SFTP('mydomain.com');
if (!$sftp->login('user', 'password')) {
exit('Login Failed');
}
$sftp->put('/some-dir/',$fileTempName);
The file however isn't being uploaded inside some-dir but is uploaded one directory before (to the starting directory, lets say it's root). This is driving me crazy, I think I've tried all combinations of some-dir/ or /some-dir or /some-dir/, but the file won't upload there.
I don't think your put is doing what you think it is doing. According to the docs, you need to do a Net_SFTP::chdir('/some-dir/') to switch to the directory you want to send file to, then put($remote_file, $data), where remote_file is the name of file, and $data is the actual file data.
Example Code:
<?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());
?>

ssh2_connect causes Error 324 (net::ERR_EMPTY_RESPONSE):

While trying to list the files present in a remote sftp location using php, I get this error:
Error 324 (net::ERR_EMPTY_RESPONSE):
The server closed the connection without sending any data. On my another lamp server the same code works fine. Please point where I am missing something if you can help please. Thanks in advance.
function listBuildFiles() {
global $sftp_host, $sftp_username, $sftp_password, $sftp_path;
$connection = ssh2_connect($sftp_host);
// Authenticate
if (!ssh2_auth_password($connection, $sftp_username, $sftp_password)) {
throw new Exception('Unable to connect.');
}
// Create our SFTP resource
if (!$sftp = ssh2_sftp($connection)) {
throw new Exception('Unable to create SFTP connection.');
}
/**
* Now that we have our SFTP resource, we can open a directory resource
* to get us a list of files. Here we will use the $sftp resource in
* our address string as I previously mentioned since our ssh2://
* protocol allows it.
*/
$files = array();
$dirHandle = opendir("ssh2.sftp://$sftp$sftp_path");
$i=0;
// Properly scan through the directory for files, ignoring directory indexes (. & ..)
while (false !== ($file = readdir($dirHandle))) {
if ($file != '.' && $file != '..') {
$files[$i] = $file;
$i++;
}
}
echo '<select name="buildName">';
echo '<option>Please Select a build</option>';
foreach ($files as $filename) {
echo "<option value=\"$filename\">$filename</option>";
}
echo '</select>';
ssh2_exec($connection, "exit");
Thanks,
Ujjwal
Just to make sure there is no problem on the server side you can open a console and try a raw ssh connection in verbose mode:
ssh -v youruser#yourhost.com
this traces all the interactions between server and client, maybe gives you some clue from the server side.
With phpseclib, a pure PHP SFTP implementation, you can see the full logs of what's going on. Example:
<?php
include('Net/SFTP.php');
define('NET_SSH2_LOGGING', NET_SSH2_LOG_COMPLEX);
$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
// puts a three-byte file named filename.remote on the SFTP server
$sftp->put('filename.remote', 'xxx');
echo $ssh->getLog();
print_r($ssh->getErrors());
?>
The developer of phpseclib is pretty proactive about providing support too so if you can't figure it out from the logs or error messages (s)he probably can.

php FTP Wrapper writes empty files (0 Byte), FTP Extension doesn't

On a server with PHP 5.2.17 running, using any function which makes use of the built in ftp wrapper to upload a file, creates an empty file on the server:
file_put_contents() returns with the accurate number of bytes
copy() also returns with true
Both create the file, but it's empty.
When trying with ftp_put() from the FTP extension, both in binary and ascii mode, it works well.
On my workstation with PHP 5.3.10 it somehow works also with the wrapper.
In code:
$source = '/tmp/testfile';
$target = 'ftp://user:pass#example.com/testfile';
copy($source, $target);
gives no error or warning, but leaves an empty file on the server.
$source = '/tmp/testfile';
$target = 'testfile';
$ftp = ftp_connect('example.com');
ftp_login($ftp, 'user', 'pass');
ftp_put($ftp, $target, $source, FTP_ASCII);
ftp_close($ftp);
works in every respect.
thanks for any suggestion!
Have you tried SSH2 libs? Some sample implementation below:
public function uploadSFTP($host_name, $port, $user, $publicSshKeyPath, $privateSshKeyPath, $remoteFile, $localFile, $fileOperation = 'w')
{
$ssh_conn = ssh2_connect($host_name, $port);
if (ssh2_auth_pubkey_file($ssh_conn, $user, $publicSshKeyPath, $privateSshKeyPath))
{
$sftp_conn = ssh2_sftp($ssh_conn);
$inputfileStream = #fopen('ssh2.sftp://' . $sftp_conn . $remoteFile, $fileOperation);
try
{
if (!$inputfileStream)
throw new Exception('Could open remote file for writing: ' . $remoteFile);
$localFileContents = #file_get_contents($localFile);
if ($localFileContents === FALSE)
throw new Exception('Could not open local file for reading :' . $localFile);
if (#fwrite($inputfileStream, $localFileContents) === FALSE)
throw new Exception('Could not SFTP file');
}
catch (Exception $e)
{
// Do something...
}
fclose($sftpInfileStream);
}
}

Categories