Php execute command no output

exec

If the output argument is present, then the specified array will be filled with every line of output from the command. Trailing whitespace, such as \n , is not included in this array. Note that if the array already contains some elements, exec() will append to the end of the array. If you do not want the function to append elements, call unset() on the array before passing it to exec() .

If the result_code argument is present along with the output argument, then the return status of the executed command will be written to this variable.

Return Values

The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

Returns false on failure.

To get the output of the executed command, be sure to set and use the output parameter.

Errors/Exceptions

Emits an E_WARNING if exec() is unable to execute the command .

Throws a ValueError if command is empty or contains null bytes.

Changelog

Version Description
8.0.0 If command is empty or contains null bytes, exec() now throws a ValueError . Previously it emitted an E_WARNING and returned false .

Examples

Example #1 An exec() example

// outputs the username that owns the running php/httpd process
// (on a system with the «whoami» executable in the path)
$output = null ;
$retval = null ;
exec ( ‘whoami’ , $output , $retval );
echo «Returned with status $retval and output:\n» ;
print_r ( $output );
?>

The above example will output something similar to:

Returned with status 0 and output: Array ( [0] => cmb )

Notes

When allowing user-supplied data to be passed to this function, use escapeshellarg() or escapeshellcmd() to ensure that users cannot trick the system into executing arbitrary commands.

Note:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

Note:

On Windows exec() will first start cmd.exe to launch the command. If you want to start an external program without starting cmd.exe use proc_open() with the bypass_shell option set.

See Also

  • system() — Execute an external program and display the output
  • passthru() — Execute an external program and display raw output
  • escapeshellcmd() — Escape shell metacharacters
  • pcntl_exec() — Executes specified program in current process space
  • backtick operator

User Contributed Notes 20 notes

This will execute $cmd in the background (no cmd window) without PHP waiting for it to finish, on both Windows and Unix.

function execInBackground ( $cmd ) <
if ( substr ( php_uname (), 0 , 7 ) == «Windows» ) <
pclose ( popen ( «start /B » . $cmd , «r» ));
>
else <
exec ( $cmd . » > /dev/null &» );
>
>
?>

(This is for linux users only).

We know now how we can fork a process in linux with the & operator.
And by using command: nohup MY_COMMAND > /dev/null 2>&1 & echo $! we can return the pid of the process.

This small class is made so you can keep in track of your created processes ( meaning start/stop/status ).

You may use it to start a process or join an exisiting PID process.

// You may use status(), start(), and stop(). notice that start() method gets called automatically one time.
$process = new Process ( ‘ls -al’ );

// or if you got the pid, however here only the status() metod will work.
$process = new Process ();
$process . setPid ( my_pid );
?>

// Then you can start/stop/ check status of the job.
$process . stop ();
$process . start ();
if ( $process . status ()) echo «The process is currently running» ;
>else echo «The process is not running.» ;
>
?>

/* An easy way to keep in track of external processes.
* Ever wanted to execute a process in php, but you still wanted to have somewhat controll of the process ? Well.. This is a way of doing it.
* @compability: Linux only. (Windows does not work).
* @author: Peec
*/
class Process private $pid ;
private $command ;

public function __construct ( $cl = false ) if ( $cl != false ) $this -> command = $cl ;
$this -> runCom ();
>
>
private function runCom () $command = ‘nohup ‘ . $this -> command . ‘ > /dev/null 2>&1 & echo $!’ ;
exec ( $command , $op );
$this -> pid = (int) $op [ 0 ];
>

public function setPid ( $pid ) $this -> pid = $pid ;
>

public function getPid () return $this -> pid ;
>

public function status () $command = ‘ps -p ‘ . $this -> pid ;
exec ( $command , $op );
if (!isset( $op [ 1 ]))return false ;
else return true ;
>

public function start () if ( $this -> command != » ) $this -> runCom ();
else return true ;
>

public function stop () $command = ‘kill ‘ . $this -> pid ;
exec ( $command );
if ( $this -> status () == false )return true ;
else return false ;
>
>
?>

Источник

exec / passthru / system execute commands but don’t return any output

Hi, I’m trying to execute some commands via the exec / shell_exec / system / passthru / popen PHP functions.
The commands are getting executed successfully, but they’re not returning any output, which they would normally do, if they are executed in a terminal/shell environment: http://i.minus.com/ipySNqCnFn5iG.png
http://i.minus.com/ibmq8Cer2yOAOR.png What I expect:

To execute a particular command and to get real-time raw output from the executed commands and display them to the browser/php page SIMULTANEOUSLY while the command is being executed. So for example, if a file is being transferred via a command, and the program being executed is supposed to return:
3764520 (1%) 1.52M/s eta:2m [Sending data] I need this exact information to be passed on to the browser / PHP script without any intervention. I am aware about the passthru function which should be used for this purpose, but all of the functions I’ve used return NO output AT ALL, while the commands itself get executed successfully without any problem.

The browser window is totally empty and no output is displayed, even though the command itself was successfully executed.

&1"; $handle = popen ($command, 'r'); while (($buffer = fgets ($handle, 4096)) !== false) < echo $buffer . "\n"; ob_flush(); flush(); >pclose ($handle); ?> 

Command(s) I’m trying to execute: executes properly, but no output displayed:
lftp -u username,password ftp.website.com -e ‘set ftp:ssl-allow off; put /var/www/folder/file.zip; bye’ 2>&1 executes properly, and output is displayed:
ls -lsra /home/username/files/

  • 2 Contributors
  • 4 Replies
  • 1K Views
  • 2 Days Discussion Span
  • Latest Post 9 Years Ago Latest Post by n21115

Have you tried to add a second argument that will hold the output of the command:

$command = "/usr/bin/lftp -u username,password ftp.website.com -e 'set ftp:ssl-allow off; put /var/www/folder/file.zip; bye'" . " 2>&1"; exec($command, $output); print_r($output); 

All 4 Replies

$command = "/usr/bin/lftp -u username,password ftp.website.com -e 'set ftp:ssl-allow off; put /var/www/folder/file.zip; bye'" . " 2>&1"; exec($command, $output); print_r($output); 

Thanks for the assistance, however, I have tried that before. It makes no difference, there is still no output to speak of. The command itself still gets executed properly, as was the case before . just that there’s no output being displayed. I tried to mess around with other commands; ‘wget’ to be specific and this time to my surprise, output WAS being displayed correctly with this:

Well, then maybe it’s got to do something with the command itself and the redirections you use. Have you tried it without the 2>&1 part or executing each part of the command sepparately (now I am guessing :-)?

After extensive research, I have finally solved this. Here’s how:
— Some specific commands in Linux don’t respond well with the different PHP functions meant to execute commands on the shell. What this means is, that the command itself would be executed, however, there would be no output caught by these PHP functions.
— The solution: make use of the ‘script’ command in Linux.
— The command that you would eventually formulate, should look something like this:
script -q -f -c «lftp -u username,password ftp.website.com -e ‘set ftp:ssl-allow off; put /path/to/file.zip; bye'» > /path/to/file.log 2>&1 &
— store the above mentioned command in a variable and use it within a command execution PHP function, such as shell_exec();
— then, PHP will execute the command and as you can notice, we ran the command as a background process. This was deliberate, as we eventually wanted to find out the PID of the LFTP process, which would be impossible if you would try to directly find the PID by echo $!; since this method would always return an incorrect PID. This is because the actual LFTP process is started AFTER php loses control over it.
— So, how do we find the LFTP process again, via PHP in order to monitor it?
— The solution: via shell_exec (); run something like this:
ps aux | grep «lftp -u username,password ftp.website.com -e set ftp:ssl-allow off; put /path/to/file.zip; bye»
— this will find the LFTP process, but how do we extract the PID out of ALL the information we just received?
— The solution: use PHP’s explode function to build an array using a single whitespace (» «) as a delimiter:
$ps_info_array = explode (» «, $ps_info);
— where $ps_info would contain the output of the ps aux | grep we did in the previous step.
— finally, ps_info_array[1] would contain the PID of the LFTP process which is currently running.
— now, we run a while loop, which would run until the LFTP process is running. We ensure this by using something like:

  • since /proc/PID is a directory always created, until a process is running on linux.
  • next, within the while loop, we need to use tail -c 79 to get the last line updated within the log file by LFTP. This will ensure we always get the latest progress as reported by LFTP.

$last_line = «tail -c 79 » . $log_file;
$currentline = shell_exec ($last_line);

  • we cannot use tail -n 1 to simply get the last line, as it would cumulate all the lines from the starting of the log file to the last line of the file and return everything, instead of just the last line. Probably due to the log file being saved being saved in the «MAC» format.
  • next, we use regular expressions to match for «(d%)» or «(dd%)» where d is a single or double digit number. This extracts the percentage completed value from the LFTP output and makes it available for use.

preg_match («/\(\d%\)|\(\d\d%\)/», $currentline, $matches);

  • the most recent percentage will now always be available in $matches[0] while the loop is running.
  • note, that, we also need to use flush(); after we echo the percentage value just found, otherwise, PHP will wait for the while loop to finish (and therefore, for the LFTP transfer to complete before reporting anything) which will defeat the purpose of our script.
  • finally, after the file file is transferred successfully, LFTP generates a confirmation message such as:
  • 197735896 bytes transferred in 86 seconds (2.20M/s)
  • this regular expression match finds this line and reports to the client that the transfer is complete.

preg_match («/bytes transferred in/», $currentline, $matches);
echo «
» . «File Transferred Successfully.»;

Источник

Читайте также:  Bitrix vm изменить версию php
Оцените статью