0. Description
In php, we can use exec()
to execute system commands, but sometimes we encounter exec( )
The command execution is unsuccessful, or there is no return. The following is an explanation:
1. Function
exec ( string $command [, array &$output [, int &$return_var ]] ) : string 参数说明: 1.$command 要执行的命令 2.$output 执行结果 3.$return_var 若同时设置 $output 和此变量,命令执行后的返回状态会被写入到此变量
2. Example
exec("ping www.baidu.com", $output);
Normally executed The result will be the same as executing ping
directly on the server, but unexpected situations may occur due to certain reasons. The following are explanations of the two situations and solutions
2.1 Permission issues
Question
When we execute Linux system commands directly on the server (here, take ping as an example), the execution permission depends on the permissions of our logged-in user. If our logged-in user isroot
, thenping
is executed using root. But when we access the website, our user at this time iswww
. If we do not modify the execution permission of ping, it will not be executed successfully.
Solution
Modify the execution permission of ping or the corresponding command
2.2 Command path problem
Problem
There is another situation, when When we use exec to execute a certain command, no error is reported or results are returned. The reason is that this command is not in the directory configured with environment variables, that is, in the/etc/profile
file, ending withifconfig
For example, we can usewhereis ifconfig
to find out the specific path of this command. For example, the path is under/usr/sbin
. There are two solutions:
Solution
1 Copy the command to/usr/bin
, which is the directory under the environment variable (not recommended)
2 Directly complete the full path of the commandexec( '/usr/sbin',$output);
(recommended)
3 Add the target directory to the environment variable, for example, add/usr/sbin
to the directory