Keep bash shell functions between shell_exec() requests - php

I have a PHP script that is run via CLI. In turn I want that script to call a bash script, but preferably I would like to break up the BASH requests so I can see the action as it is happening.
I can seem to set Environmental variables and they seem to exist between shell_exec() functions. But even when I have a source file like:
source ./bashes/functions.sh
And in the source file I use "export -f function-name" to export the functions in the script before executing the next line, the next line does not see the functions.
$file = file('./bashes/bash_testing.sh',FILE_SKIP_EMPTY_LINES);
//we want to watch this in realtime so write each line seperately to shell.
foreach($file as $command) {
$output->writeln(shell_exec($command));
}
The function $output->writeln is a helper function just to echo the returned result. But basically the error I get is
sh: now: command not found
now is defined as a function in the included bash_testing.sh shell script.
Anyone know how I can resolve this issue?
Here is the source to the ./bashes/functions.sh file:
function now {
date -u +%T
}
export -fx now

There is a way to maintain a single bash shell, execute commands and handle the return. I recently published a project that allows PHP to obtain and interact with a real Bash shell. Get it here: https://github.com/merlinthemagic/MTS
I would suggest not triggering a bash script but rather trigger the induvidual commands. That way you can handle the return and not have to build exception handling in bash.
After downloading you would simply use the following code:
//get a real bash shell.
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', false);
$return1 = $shell->exeCmd($command1);
//logic to handle the return
$return2 = $shell->exeCmd($command2);
//logic to handle the return
..... etc

Related

php call scrapy by custom command

I have to run my five different scrapy spiders at the same time so I define a custom command in scrapy like
scrapy crawlall
to call these spiders. It works successfully when I run in command line in independent.
However it fails when I use php shell_exec to call the same command and the code in php file is like
$cmd = 'scrapy crawlall';
$results = shell_exec($cmd);
echo $results;
The web page will echo nothing immediately and not waiting the scrapy function(or even it wasn't be called at the beginning I don't know). So how can I call this command or other way to run these 5 spiders at the same time in php file? Thanks!
I have solved the problem. If you get the same situation, try to remove all comment in your command python file. I don't know the reason but after I do that it works successful.

Pageres using PHP exec

I'm using Pageres to capture a Highcharts chart. I have a PHP script that takes in an argument to generate the proper URL and file name for the pageres command. When I go to use PHP's exec command, it fires off a bunch of pageres commands and never actually completes the pageres command. The pageres command works perfectly from the command line though.
Snippet of my PHP code:
$cmd = "pageres http://localurl/wriphp/visGraph.php?port=".$port." 1100x200 --filename ".$port;
exec($cmd);
Why does the php exec call run out of control?

PHP: run "mkdir" and get errno

I need to execute mkdir command (e.g. via PHP's exec command). How do I access standard error (e.g. EACCES, see: http://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html). Suggestions? Thanks.
UPDATE:
I added 2>&1 to my command:
$command = "sudo mkdir /home/test 2>&1";
$output = array();
$return = 0;
exec($command, $output, $return);
Without it, I used to get either 0 (success) or -1 (error). Now, I get a 1 during one of my tests -- and I think it's because the directory I am trying to create already exist. It would seem that 1 maps to EEXIST. How do I map the rest of the errno?
You cannot.
You want to catch the error of the mkdir function via errno, but your call to PHP's exec() means that you will instead deal with the exit code of the external program mkdir.
It is the difference between:
http://pubs.opengroup.org/onlinepubs/009695399/functions/mkdir.html (which you cite)
and
http://pubs.opengroup.org/onlinepubs/009695399/utilities/mkdir.html (which you exec)
You're probably looking for proc_open, which gives you the ability to work directly with stdin, stdout and stderr as PHP streams, meaning you can use the normal file reading and writing functions on them.
Please be sure to read more details about the proc_ family tree on the proc_close and proc_get_status pages.
You might have more luck working with the text of the error as provided to stderr instead of working with exit codes.

Executing cmd commands in Windows from PHP Issue

Is it possible to execute cmd commands in Windows OS with PHP exec() function?
I tried this:
<?php
try {
echo exec(
'O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf'
);
} catch (Exception $e) {
echo $e->getMessage();
}
Basically, I'm trying to merge two pdf files with the pdftk program. If I just write the same exact command to the cmd by hand, it works and the O:\test\123.pdf file is created. But when I execute the above PHP file, nothing happens (blank page, the file is not created).
Can your PHP user access cmd.exe? You might find the tools at Microsoft's Sysinternals very useful; particularly the process monitor.
Try escaping the directory separator:
exec("O:\\test\\pdftk.exe O:\\test\\outputs\\OPP\\out.pdf O:\\test\\outputs\\OPP\\out2.pdf cat output O:\\test\\123.pdf");
Or even better, use single quotes instead:
exec('O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf');
Here is a project that allows PHP to obtain and interact dynamically with a real cmd terminal. Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
//if you prefer Powershell, replace 'cmd' with 'powershell'
$shellObj = \MTS\Factories::getDevices()->getLocalHost()->getShell('cmd');
$strCmd1 = 'O:\\test\\pdftk.exe O:\\test\\outputs\\OPP\\out.pdf O:\\test\\outputs\\OPP\\out2.pdf cat output O:\\test\\123.pdf';
$return1 = $shellObj->exeCmd($strCmd1);
The return will give you the command return OR error from cmd, just as if you sat at the console. Furthermore, you can issue any command you like against the $shellObj, the environment is maintained throughout the life of the PHP script. So instead of bundling commands in a script file, just issue them one by one using the exeCmd() method, that way you can also handle the return and any exceptions.
try Executing using the Admin Privileges for command prompt

Can't execute PHP script using PHP exec

I am trying to invoke a script which takes several seconds (web services with 3rd party) using the PHP exec call. After much struggling, I reduced this to the classic hello world example. The calling script looks like:
exec('/usr/bin/php /home/quote2bi/tmp/helloworld.php > /tmp/execoutput.txt 2>&1 &');
When I run this, the output execoutput.txt contains a copy of the invoking script page, not hello world as I expected.
Why can't I get this PHP script to execute using exec? Note that when I change the command to something like ls -l, the output is a directory listing as expected. btw, in case it matters, I did chmod the called script to 755...
Update - I moved the exec call to the end of the calling script and at least now I don't see the calling script executed in the output. Thx to posters and I will try some of these ideas.
Help!
Thanks
Steve
I had this issue also and it turns out this is a bug in php (#11430). The fix is to use php-cli when calling another php script within a php script. So you can still use exec but rather than use php use php-cli when calling it in the browser:
exec("php-cli somescript.php");
This worked for me.
What exec is doing is taking the rightmost command and appending it to your destination. If you have the shebang line in your php script, you shouldn't need to include the binary directive of the php interpreter.
if you just want the script's output, try:
exec('/home/quote2bi/tmp/helloworld.php > /tmp/execoutput.txt 2>&1 &')
however if you do not want the errors to be in the file, you should redirect the STDERR prior to outputting to the file. Like so:
exec('/home/quote2bi/tmp/helloworld.php 2> /dev/null > /tmp/execoutput.txt')
the above should only output the "Hello World" to the execoutput.
Edit:
Interesting you are getting this behaviour. You stated the command "ls" worked. Try making an alias for this and forward it to a file like so:
alias pexec='php /home/quote2bi/tmp/helloworld.php'
then
exec('pexec > /tmp/execoutput.txt 2>&1 &')
it seems to be a problem with the way exec handles input as opposed to the shell itself.
-John
The problem is with PHP itself, it treats everything as $argv in the script. It doesn´t redirect the output to a file ou to /dev/null.
I faced the same problem some time ago. What I did is to create a runscript.php in /opt/php-bin and then inside this script run what It should be running. Something like this:
$script = $argv[1]
$params = implode(' ', array_slice($argv, 2));
$cmd = "{$script} {$params} > /dev/null &";
$output = array();
$return = 0;
exec("php {$cmd}", $output, $return);
exit((int)$return);
And then you call it using:
exec('/opt/php-bin/runscript.php /path/to/your/script.php arg1 arg2')
It´s the only way I managed to get this working.
To avoid the stated problems of PHP in this area, why not put this in inside a shell script? PHP can then execute the shell script which has all the redirections handled internally.
If you need to dynamically change things, then why not write the shell script and then execute it (and of course, clean up afterwards)?
if you are just simply running a php script one possible way to execute the entire code is to use the include() that will run the php file and output any results. You cannot direct the output to a text file but it should appear in the browser window if you're Hello World php script looks like
<?php echo "Hello World!"; ?>
then it will spit that out in the browser. So your second code would look like
<?php include("helloWorld.php"); echo " PHP ROCKS";?>
resulting in a page that would look like,
Hello world! PHP ROCKS
This runs as if you run the script from browser.
This came across while working on a project on linux platform.
exec('wget http://<url to the php script>)
Hope this helps!!

Categories