Execute find command through ssh2_exec in php & get results - php

I am using php to execute a find command in linux for search a file in a directory and copy it into a other directory.
My php code is :-
<?php
include 'config.php';
$mxf = $_POST['year'];
$year = substr($mxf, 0, 4);
$ndrive = $_POST['ndrive'];
$command = 'find /var/www/html/collections/'.$year.'/ -name ' . $mxf . ' -exec cp {} ' . $ndrive . ' \;';
$stream = ssh2_exec($con, $command);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);
ssh2_exec($con, 'logout');
?>
Now i want that script return false if requested file is not found in directory or file not available on server. So how can i handle this type of error with ssh2_exec command.

Related

Running commands from PHP exec shows different result than from shell

The PHP exec command is not executing the same as the shell's interaction.
cd /var/www/myfolder
zip -r /var/www/myfolder/temp/newfile.zip ./*
generates just a zip of files in the temp directory. However (simplified version):
$zip_dir = '/var/www/myfolder';
$temp_dir = $zip_dir . '/temp/';
chdir($zip_dir);
exec('zip -r ' . $temp_dir . 'newfile.zip ./*', $return);
generates the same zip but with the full path's of var and www (which results in two copies of myfolder so my file is twice as large as needed). The $return however has the same output as the command line execution. Both state only 15 files directories/folders were zipped. There is no mention of var or www in the PHP output.
I believe the chdir() command will not have any bearing on how the commands in exec() are run. So this might fix it:
$zip_dir = '/var/www/myfolder';
$temp_dir = $zip_dir . '/temp/';
$cmd = 'cd ' . escapeshellarg($zip_dir) . ' && zip -r ' . escapeshellarg($temp_dir . 'newfile.zip') . ' ./*';
exec($cmd, $return);
Note we always escape variables being passed to the command line.
But why not just zip within PHP?
<?php
$zip_target = "/var/www/myfolder";
$zip_file = "/var/www/myfolder/temp/newfile.zip";
$zip_temp = tempnam(sys_get_temp_dir(), 'a458');
$zip_obj = new \ZipArchive();
if ($zip_obj->open($zip_temp, ZIPARCHIVE::OVERWRITE)) {
$zip_obj->addGlob("$zip_target/**/*.*");
}
$zip_obj->close();
rename($zip_temp, $zip_file);

7zip command executes from command line but not within php script

I am attempting to write a script which automatically unzips 7zip archives. I'm able to get the command to run from the command prompt, but it doesn't work when running from within the php script.
Here's what I have in terms of code:
$filefolder = "F:/dev/";
$filename = "archive.7z";
$filepath = $filefolder . $filename;
$unzip = "cmd /c 7z x " . $filePath . " -o" . $fileFolder . " -spf";
print_r($unzip . "<br>"); //checking to make sure the command is formed correctly
exec($unzip, $outcome, $rtnStatus);
print_r($outcome);
print_r($rtnStatus);
The following is returned for $outcome and $rtnStatus:
Array ( )
1
What am I missing here?

file is not running via Shell_exec in php

my code is as below . this will not help me to run this file run_ques.php via shell_exec
$location = $cron_file_location . "/run_ques.php";
$shell_command = "php {$location} > /dev/null &";
shell_exec($shell_command);
echo $cron_file_location;
echo "test";
echo $shell_command;
die();

Make PHP wait for Matlab script to finish executing [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php exec command (or similar) to not wait for result
exec() waiting for a response in PHP
I have a php script that calls and runs a Matlab script. The result of the Matlab script is a .png image, which I would then like to load in php and send to a webpage. The php code I have is:
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
passthru($command);
$im = file_get_contents('C:\\habitat.png');
header('Content-type:image/png');
echo $im;
However, it appears that after sending the 'passthru' command, php does not wait for the Matlab script to finish running. Thus, if the image file does not exist before running the php code, then I get an error message.
Is there a way to make it so that the php code waits for the Matlab script to finish running before it attempts to load the image file?
passthru is not the main issue here .. but i guess as soon you have a response from your command the image is not written instantly but by a 3rd process
file_get_contents might also fail in this instance because .. The image might not be written once or in the process of writing which can result to file lock .. in any case you need to be sure you have a valid image before output is sent;
set_time_limit(0);
$timeout = 30; // sec
$output = 'C:\\habitat.png';
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
try {
if (! #unlink($output) && is_file($output))
throw new Exception("Unable to remove old file");
passthru($command);
$start = time();
while ( true ) {
// Check if file is readable
if (is_file($output) && is_readable($output)) {
$img = #imagecreatefrompng($output);
// Check if Math Lab is has finished writing to image
if ($img !== false) {
header('Content-type:image/png');
imagepng($img);
break;
}
}
// Check Timeout
if ((time() - $start) > $timeout) {
throw new Exception("Timeout Reached");
break;
}
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
I believe if you change passthru to exec it will work as intended. You can also try this:
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
passthru($command);
// once a second, check for the file, up to 10 seconds
for ($i = 0; $i < 10; $i++) {
sleep(1);
if (false !== ($im = #file_get_contents('C:\\habitat.png'))) {
header('Content-type:image/png');
echo $im;
break;
}
}

When tried to run following PHP script gives error on Windows 7

if (strlen($log) > 0)
{
// Use "WScript.Shell" to run the command with no command prompt window pop up.
$wShell = new COM("WScript.Shell");
$cmd = "cmd /c cscript.exe \"%DIR%\\bin\\eventquery.vbs\" /l \"" . $log . "\" > \"%DIR%\\Temp\\event.log\" 2>&1";
////echo $cmd;
$return = $wShell->Run($cmd, 0, true);
if ($return == 0 || $return ==254)
{
$handle = #fopen(getenv('DIR') . "\\Temp\\event.log", "r");
if ($handle)
{
$linenum = 1;
while (!feof($handle))
{
$buffer = fgets($handle);
// Skip the first three lines
if ($linenum > 3)
{
echo $buffer;
}
$linenum++;
}
fclose($handle);
}
}
else
{
echo "Error running \"" . $cmd . "\" command.";
}
}
It gives an error on windows 7:
ERROR: Unable to include the common module"CmdLib.Wsc"
When I try run it from command line# windows 7, it works fine:
cscript.exe \"%DIR%\\bin\\eventquery.vbs\" /l \"" . $log . "\" > \"%DIR%\\Temp\\event.log\" 2>&1
Try using escapeshellarg:
$cmd = "cmd /c cscript.exe \"%DIR%\\bin\\eventquery.vbs\" /l \"" . escapeshellarg($log) . "\" > \"%DIR%\\Temp\\event.log\" 2>&1";
My guess is that you have shell metacharacters in $log.`
$a = 'all';
file_put_contents('ip.txt',shell_exec($dump = sprintf('ipconfig /%s',$a)));

Categories