I have the following code which doesn't seem to work, however it works when I open up a command prompt and run the command:
Provide target PC names [separate with ":"]:
How come it works in the command prompt but not when I execute it via PHP? I am trying to restart a Windows PC remotely.
[PHP 4, PHP 5, PHP 7, PHP 8]
shell_exec — Execute command via shell and return the complete output as a string
Description
shell_exec[string $command
]: string|false|null
Note:
On Windows, the underlying pipe is opened in text mode which can cause the function to fail for binary output. Consider to use popen[] instead for such cases.
Parameters
command
The command that will be executed.
Return Values
A string containing the output from the executed command, false
if the pipe cannot be established or null
if an error occurs or the command produces no output.
Note:
This function can return
null
both when an error occurs or the program produces no output. It is not possible to detect execution failures using this function. exec[] should be used when access to the program exit code is required.
Errors/Exceptions
An E_WARNING
level error is generated when the pipe cannot be established.
Examples
Example #1 A shell_exec[] example
See Also
- exec[] - Execute an external program
- escapeshellcmd[] - Escape shell metacharacters
trev at dedicate.co.uk ¶
10 years ago
If you're trying to run a command such as "gunzip -t" in shell_exec and getting an empty result, you might need to add 2>&1 to the end of the command, eg:
Won't always work:
echo shell_exec["gunzip -c -t $path_to_backup_file"];
Should work:
echo shell_exec["gunzip -c -t $path_to_backup_file 2>&1"];
In the above example, a line break at the beginning of the gunzip output seemed to prevent shell_exec printing anything else. Hope this saves someone else an hour or two.
smcbride at msn dot com ¶
1 year ago
proc_open is probably a better solution for most use cases as of PHP 7.4. There is better control and platform independence. If you still want to use shell_exec[], I like to wrap it with a function that allows better control.
Something like below solves some problems with background process issues on apache/php. It also
public function sh_exec[string $cmd, string $outputfile = "", string $pidfile = "", bool $mergestderror = true, bool $bg = false] {
$fullcmd = $cmd;
if[strlen[$outputfile] > 0] $fullcmd .= " >> " . $outputfile;
if[$mergestderror] $fullcmd .= " 2>&1";
if[$bg] {
$fullcmd = "nohup " . $fullcmd . " &";
if[strlen[$pidfile]] $fullcmd .= " echo $! > " . $pidfile;
} else {
if[strlen[$pidfile] > 0] $fullcmd .= "; echo $$ > " . $pidfile;
}
shell_exec[$fullcmd];
}
alexandre dot schmidt at gmail dot com ¶
6 years ago
To run a command in background, the output must be redirected to /dev/null. This is written in exec[] manual page. There are cases where you need the output to be logged somewhere else though. Redirecting the output to a file like this didn't work for me: