Phpseclib blocked when sftp->get or sftp->put is called - php

I have to monitor the upload and download speed of a Raspberry to an SFTP server.
Such I have to put this data after on a website, at first I thinked to the old library ssh2 of PHP but it didn't send nothing as demanded on the server.
Like Phpseclib exist and seems to be more soft, I have installed Phpseclib on the Raspberry PI by composer. I think that everything is normally installed as some tutorial on website but when I'm using get and put like in the attachment code, CLI command freezes with get.php and give me nothing on the screen and put.php is giving the same time for a file of 1Mo as 512Ko (60 seconds) :/
Do you know how solve this kind of problem ? I had wait 15 min front of the CLI but she seems freezed.
Thanks a lot for your help !
Put.php
`<?php
include '/home/pi/vendor/autoload.php';
$sftp = new \phpseclib\Net\SFTP('192.168.100.20');
$key = new \phpseclib\Crypt\RSA();
$key->loadkey(file_get_contents('/home/pi/.ssh/id_rsa.pub'));
$key->loadkey(file_get_contents( '/home/pi/.ssh/id_rsa'));
if (!$sftp->login('vdar', $key)) {
exit('Login Failed');
}
$start = microtime(true);
$sftp->put('test.txt', str_repeat('a',1024*512));
$elapsed = microtime(true)-$start;
echo "took $elapsed seconds";
?>`
Get.php
`<?php
include '/home/pi/vendor/autoload.php';
define('NET_SFTP_LOGGING', NET_SFTP_LOG_COMPLEX);
$sftp = new \phpseclib\Net\SFTP('192.168.100.20');
$key = new \phpseclib\Crypt\RSA();
$key->loadkey(file_get_contents('/home/pi/.ssh/id_rsa.pub'));
$key->loadkey(file_get_contents( '/home/pi/.ssh/id_rsa'));
if (!$sftp->login('vdar', $key)) {
exit('Login Failed');
}
echo $sftp->pwd() . "\r\n";
$filename='remoteTest.txt';
if($filename)
{
$local_file_path='localTest.txt';
$sftp->get($filename, $local_file_path);
}
else
{
echo "error download files";
}?>`

Related

Export as PDF Using PHP COM

I want to convert an Excel file to PDF.
Here is my code:
function excel() {
$excel = new COM("Excel.Application") or die ("ERROR: Unable to instantaniate COM!\r\n");
$file = base_url('archieve/ADAF - 2018000007.xlsx');
$Workbook = $excel->Workbooks->Open($file) or die("ERROR: Unable to open " . $file . "!\r\n");
$Worksheet = $Workbook->Worksheets(1);
echo 'file loaded';
$xlTypePDF = 0;
$xlQualityStandard = 0;
try {
$Worksheet->ExportAsFixedFormat($xlTypePDF, base_url('archieve/ADAF test.pdf'), $xlQualityStandard);
} catch(com_exception $e) {
echo $e->getMessage()."\n";
exit;
}
echo 'file convert';
$excel = NULL;
unset($excel);
}
When I run the function, the server is still loading and reaches timeout. The code is in a different server.
Is my code wrong? Since I have tested in local PC and it works.
I tried to run the COM using Python and it worked fine. Turns out there is a problem in PHP when export as pdf. I still have the issue. Any suggestions?

Separate PHP processes using same ssh2.sftp resource

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');

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.

Zip File created with PHP shows on localhost but not on server

I am new to PHP and here is my dilemma. I am trying to add to my site a feature that allows users to select a set of images in Flash (AS3) click a button and have my server create a zip file of all the images for them to download.
I have already wrote my code in flash and crated my php script and tested it on my localhost and everything works great. But when I upload the same files to my sever no zip files are created. Below is the code for both my flash and for my php. Any help or tips would be appreciated I am struggling over her.
Localhost server is using 5.2.17 and so if my Server hosted on 1&1
Flash Code To Send Info to PHP
function MakeZip():void
{
var variables:URLVariables = new URLVariables();
//variables.Image1=img1;
variables.ImageList=OrderItems;
variables.Name= zipName_txt.text + ".zip";
variables.FileComplete="File Created";
var request:URLRequest = new URLRequest();
request.url="ArrayTest.php";
request.data=variables;
var loader:URLLoader = new URLLoader();
loader.load(request);//sends the request
//when the request is done loading, it goes to the completeWriting function
loader.addEventListener(Event.COMPLETE, completeWriting);
loader.addEventListener(IOErrorEvent.IO_ERROR, error);
function completeWriting(event:Event):void
{
info_txt.text = "File Created";
}
function error(e:IOErrorEvent):void
{
info_txt.text = "There was an error. Please try again later.";
}
}
PHP to create file
<?PHP
$zipName= $_GET['Name'];
$Order= $_GET['ImageList'];
$fileList = explode('|',$Order);
$ZipComplete = $_GET['FileComplete'];
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
// add files
foreach ($fileList as $f) {
$zip->addFile($f) or die ("ERROR: Could not add file: $f");
print false;
}
// close and save archive
$zip->close();
//writeVariable( "ZipComplete", $ZipComplete);
echo "FileComple=" . $ZipComplete;
?>
Thank you all for your tips and hints. After hours of trying different things I found the mistake was in my flash code. On my localhost it ignores capitalization for file names. On my server however it does not ignore it. I had in my flash file image1.jpg but the file name is actually Image1.jpg. Glad I found it bit it is so frustrating how a little thing like that made it not work.
is there any error response returned from you php script?
please make sure the zip file save path on server is correct and have write access
This is because code is running as "nobody" on server. This user would not have write access to anywhere except /tmp .
Add following code, this should work:
<?PHP
$zipName= $_GET['Name'];
$Order= $_GET['ImageList'];
$fileList = explode('|',$Order);
$ZipComplete = $_GET['FileComplete'];
// create object
$zip = new ZipArchive();
$zipName = "/tmp/" + $zipName;
// open archive
if ($zip->open($zipName, ZIPARCHIVE::CREATE) !== TRUE) {
die ("Could not open archive");
}
$zipName = "/tmp/" + $zipName; is the key part.

Categories