start .php skript asynchron over PHP and answer to requests - php

I try to start a .php script asynchron from an other php script.
if (substr(php_uname(), 0, 7) == "Windows"){
$cmd = "start /B php AsynchronDownload.php fileids=".$this->header->queryParams['ids'] . " uid=".$this->header->tokenData->uId . " groupId=".$this->header->tokenData->groupId . " timestamp=".$this->header->tokenData->timestamp . " state=".$this->header->tokenData->state. " token=".$this->header->tokenData->token;
pclose(popen($cmd, "r"));
} else {
$cmd = "/usr/bin/php7.2-cli AsynchronDownload.php fileids=".$this->header->queryParams['ids'] . " uid=".$this->header->tokenData->uId . " groupId=".$this->header->tokenData->groupId . " timestamp=".$this->header->tokenData->timestamp . " state=".$this->header->tokenData->state. " token=".$this->header->tokenData->token;
exec($cmd . " > /dev/null &");
}
Thats work fine. But is it possible to awnser to an Http Request, how is send to the first skript from a client in the second asynchron started skript? I found out the details about the Request are not available on the second skript.
If I try to set Headers for the Response with (for example) header('Content-type: x-zip') they are not set. headers_list() funktion returning NULL.

Related

py file call successful but no output

im trying to execute an py file from php, using bat file .
the whole code works fine and im trying to execute an file name dbConn.py
the file executes when seperatly double clicked i.e executed and output is reflected
the code from php is this:
if ($conn->query($sql) === TRUE) {
mysqli_close($conn);
$cmd = "run_dbConn.bat" ;
execInBackground($cmd);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
This is code for runcmd.php
<?php
function execInBackground($cmd) {
if (substr(php_uname(), 0, 7) == "Windows"){
pclose(popen("start /B ". $cmd, "r"));
}
else {
exec($cmd . " > /dev/null &");
}
}
?>
and code for run_dbConn.bat
cd C:\xampp\htdocs\eclipse_workspace\Project
python dbConn.py
ECHO %1
echo
even the above code make the file to run , which i have checked from task bar. but the output is not generated or reflected. the dbConn.py does not have something related to code and can be executed separately....
plzz help me out even a suggestion will be well.
exec($cmd . " > /dev/null &");
This line will run the command and redirect the output to a null device, aka hides the output.
Try removing
> /dev/null

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?

PHP passing parameters to a background script

I've been looking for quite a while on internet, but I cannot find a solution to my problem. I am pretty new to PHP, and I am having issues to run a php script in background.
Basically, I am getting POST data from JQuery ajax, I put it in a long string using escapeshellarg() on each variable and separated by spaces, and I call the script I want to process in background with exec() or shell_exec() functions (I tried both without any success...).
$arg_list = escapeshellarg($str_solution)." ";
$arg_list .= escapeshellarg($str_rubriques)." ";
$arg_list .= escapeshellarg($intervalle)." ";
$arg_list .= escapeshellarg($date_start)." ";
$arg_list .= escapeshellarg($date_end)." ";
$arg_list .= escapeshellarg($_SESSION['user_id'])." ";
$arg_list .= escapeshellarg($_SESSION['user_name']);
//BACKGROUND EXECUTION
$output = shell_exec("/opt/plesk/php/5.6/bin/php-cgi -q script_rapports_intervalle.php ".$arg_list." &");
print_r($output);
On the script_rapports_intervalle.php file, I just do :
print_r($argv);
print_r("here i am");
die;
//HERE GOES THE SCRIPT
//....
I do got a response from this script, as it displays only the "here i am" string. When I use a var_dump() on $argv, it says it is NULL. I have also tried to pass simple arguments like "foo" and "bar", but it seems that $argv is always equal to NULL.
Moreover, I saw many usages for processing a background script: putting "&" at the end of the command, or putting "| at now" instead. Which one should I use?
I guess I am surely doing things the wrong way, but I still cannot see where to fix the issues.
For me this simple code works
$params = array("function_name" => 'image_detect',"image_guid" => $image_guid);
$query_string = http_build_query($params, "", " ");
if (PHP_OS === "WINNT") {
pclose(popen("start /B php " . $script_location . " " . $query_string, "r"));
} else {
exec("/opt/plesk/php/5.6/bin/php " . $script_location . " " . $query_string . " &> /dev/null &");
}
So in your case you can check by replacing /opt/plesk/php/5.6/bin/php-cgi with /opt/plesk/php/5.6/bin/php

Executing AppleScript with PHP shell_exec() and OSAScript

My goal is to be able to submit a search query from a web form and have an AppleScript execute the search in DEVONagent. The AppleScript works fine in terminal but I get an error when having PHP do a shell_exec().
<?php
$theQuery = $_GET["Query"];
$cmd = "theSearch=\"$theQuery\" osascript -e \"set theSearch to system attribute " . "\\" . "\"theSearch" . "\\" . "\"\" -e \"tell application " . "\\" . "\"DEVONagent" . "\\" . "\"\" -e \"search theSearch using set " . "\\" . "\"Web (Deep Link)" . "\\" . "\"\" -e \"end tell\" 2>&1";
echo "<pre>$cmd</pre><BR><BR>";
$theResponse = shell_exec ( $cmd );
echo "Your search for \"$theQuery\" has started and the results will be emailed to you once complete.";
echo "<pre>$theResponse</pre>";
?>
I end up with the following error from the $theResponse echo:
83:92: syntax error: Expected end of line but found identifier. (-2741)
I'm thinking maybe a permissions thing but I just cannot figure it out.

PHP LFTP data mirror output

I'm using a Linux local computer and need to backup/mirror some very large file structures regularly. I only have access to SFTP.
I was after a simple one click solution. I originally tried to write the little script in BASH but I've never used it before and am not up to scratch with the syntax so I resorted to PHP. (I do understand PHP is not designed for this kind of work, but I'm on a tight time scale and don't have the time to get into BASH atm)
<?php
//init
parse_str(implode('&', array_slice($argv, 1)), $_GET);
$error = array();
$lPrefix = '/home/hozza/Sites/';
$archiveLocation = '/home/hozza/Backups/';
$lDir = isset($_GET['l']) ? $_GET['l'] : $error[] = 'Local Directory Required';
$rDir = isset($_GET['r']) ? $_GET['r'] : $error[] = 'Remote Directory Required';
$bookmark = isset($_GET['b']) ? $_GET['b'] : $error[] = 'lftp Bookmark Required';
//Check for args
if(count($error) == 0) {
$archiveName = end(explode('/', $lDir)) . '_' . date('Y-m-d_H-i');
//Validate local dir
if(is_dir($lPrefix . $lDir)) {
//preserve Sublime Text 2 config SFTP files
$ST2_SFTP_conf = false;
if(file_exists($lPrefix . $lDir . '/sftp-config.json')) {
$ST2_SFTP_conf = file_get_contents($lPrefix . $lDir . '/sftp-config.json');
unlink($lPrefix . $lDir . '/sftp-config.json');
}
//Start mirror
$lftOutput = explode("\n", shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark));
//Tar regardless of lftp error or success
$tarOutput = shell_exec('cd ' . $lPrefix . ' && tar -czf ' . $archiveLocation . $archiveName . '.tar.gz ' . $lDir);
//Output completion or errors
shell_exec('notify-send -i gnome-network-properties -t 0 "Mirror & Archive Complete" "' . $archiveName . '\n\n' . implode('\n', $lftOutput) . $tarOutput . '"');
//put back ST2 SFTP conf
if($ST2_SFTP_conf != false) file_put_contents($lPrefix . $lDir . '/sftp-config.json', $ST2_SFTP_conf);
exit;
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . $lDir . ' \n Does not exist! D:"');
}
else shell_exec('notify-send -i error -t 0 "Mirror & Archive Error" "' . date('Y-m-d') . ' ' . date('H-i') . '\n' . implode('\n', $error) . '"');
?>
It can be run for many sites via a short-cut like so...
terminator -T "Mirror & Archive" -e "php ~/Programs/mirror.php l=local-dir_path r=./ b=lftp-bookmark-name"
If no password is in the LFTP bookmark (there shouldn’t be as it's stored in plain text) the terminal prompts for a password, after the script has run, a nice notification is given with some info about files/folders/speed etc.
However, when the script is running in a terminal, only the "input password" bit is output to the terminal, I would like all the output displayed in the terminal (normally that would display what file/folder is currently working with etc.)
Anyone know how to do that?
IIRC the reason that you see the password prompt output to the terminal is that it is using stderr. You could try redirecting stdout to stderr for your commands which should show you the 'real-time' progress. Tack this on to the end of the shell_exec() command: 1>&2
ie:
shell_exec('lftp -e "mirror -e -p --parallel=10 --log=' . $archiveLocation . 'logs/' . $archiveName . '.txt ' . $rDir . '/ ' . $lPrefix . $lDir . '/; exit top" ' . $bookmark . ' 1>&2')
However, this will preclude you from having anything returned by shell_exec for logging purposes. What I would suggest is something like:
$log_stem = '/tmp/' . time() . '_'; // ie: /tmp/1357581737_
$lfOutfile = $log_stem . 'lftp.log';
$tarOutfile = $log_stem . 'tar.log';
shell_exec('lftp -blah | tee ' . $lfOutfile ' 1>&2' );
shell_exec('tar -blah | tee ' . $tarOutfile ' 1>&2' );
$lfOut = file_get_contents($lfOutfile);
$tarOut = file_get_contetns(tarOutfile);
// remove tmp files
unlink($lfOutfile);
unlink($tarOutfile);
Which will capture a copy of the output to a file before redirecting the output to stderr so you can watch it live.
However, if you want to run this via cron I would recommend against writing anything to stderr that is not an error, otherwise cron will send a warning email every time it is run.
I think the last answer was close:
Either this:
shell_exec('lftp -blah |& tee ' . $lfOutfile );
shell_exec('tar -blah |& tee ' . $tarOutfile );
Or if that still doesn't work try this:
shell_exec('lftp -blah 2>&1 | tee ' . $lfOutfile );
shell_exec('tar -blah 2>&1 | tee ' . $tarOutfile );

Categories