could not copy file name with space in scp ssh - php

I could not copy the file with spaces in file name using ssh2_scp_recv() function.This is the filename testfile-03_23_15 11 02 AM.csv which actually stored in server.
my code is here
if ($file == "testfile-03_23_15 11 02 AM.csv"){
if(!ssh2_scp_recv($connection,$remoteDir .$file, $localDir . $file)){
echo "Could not download: ", $remoteDir, $file, "\n";
}
}
Please help me if you know.
Thanks.

With phpseclib:
<?php
include 'phpseclib/Net/SSH2.php';
include 'phpseclib/Net/SCP.php';
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('bad login');
}
$scp = new Net_SCP($ssh);
$scp->get('file name with spaces');

Try this one:
ssh2_scp_recv($connection,"\"".$remote_file_name."\"",$local_path."/".$remote_file_name);
Source: php.net
It says: Trying to get a remote file with spaces in its name?
Never forget to use quotes in the remote filename, but never in the local one.

Related

deleting all files from a folder on Linux server using PHP

My question is almost the same as this one Deleting all files from a folder using PHP?
And I tried to use the answer provided by #Floern https://stackoverflow.com/a/4594262/2167772
But it didn't work for me. I tried to get filenames from a folder on the Linux server. And I have changed the folder and file permission to rwxrwxrwx. And I got the "Unable to get the filename" message all the time. Does anyone know how to solve it? Thanks a lot!
$files=glob('/data/in/*') or die ("Unable to get the filename");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
unlink($file) or die ("Uable to delete file!");
}
}
------Update----
I just figured it out. It is the problem with the server. I cannot write anything to the data folder even I assign the write permission. I will move my in folder to another folder.
Thank you so much for everyone's comments!
As said #Marc B, you just have to write this :
$files=glob('data/in/*') or die ("Unable to get the filenames!");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
unlink($file) or die ("Unable to delete file!");
}
}
You write : glob('/data/in/*'), I write glob('data/in/*')
You use absolute path, i use relative path.
Use this tutorial:
http://de3.php.net/manual/de/function.rmdir.php#107233
And check is your folder permission is enable to write.
Have you trying like this:
$dir = 'your/directory/';
foreach(glob($dir.'*.*') as $v){
unlink($v);
}
if file is not at public directory...
change mode of file to 777
$files=glob('data/in/*') or die ("Unable to get the filename");
foreach ($files as $file) {
if(is_file($file)){
echo $file;
chmod($file,777);
unlink($file) or die ("Uable to delete file!");
}
}
solution with php. don't like the glob function. you can use the RecursiveDirectoryIterator
$filePath = '/someDir';
$directoryIterator = new \RecursiveDirectoryIterator(realpath($filePath));
foreach (new \RecursiveIteratorIterator($directoryIterator) as $object ) {
if(!$object->isDir())
{
unlink($object->getPath());
}
}

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