Home  >  Article  >  Backend Development  >  Solution to the problem that the exec() function in PHP fails to execute system commands

Solution to the problem that the exec() function in PHP fails to execute system commands

不言
不言forward
2019-02-15 11:41:088083browse

This article brings you the solution to the problem of the exec() function in PHP failing to execute system commands. It has certain reference value. Friends in need can refer to it. I hope it will help You helped.

0. Description

In php, we can use exec() to execute system commands, but sometimes we encounter unsuccessful execution of the exec() command. Or if there is no return, please explain below:

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);

Normal Generally speaking, the execution result will be the same as executing ping directly on the server, but due to some reasons, unexpected situations may occur. The following is an explanation of the two situations and the solution

2.1 Permission issues

Question

When we execute Linux system commands directly on the server (taking ping as an example here), the execution permissions depend on the permissions of our logged-in user. If our logged-in user is root, Then when executing ping, it is executed as root. But when we access the website, our user at this time is www. If we do not modify the execution permission of ping, it will not be executed successfully.

Solution

Modify the execution permissions of ping or corresponding commands

2.2 Command path problem

Problem

There is another situation. When we use exec to execute a command, no error is reported and no result is returned. The reason is that this command is not in the directory configured with environment variables, that is, the /etc/profile file. To ifconfig For example, we can use `whereis
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 (not recommended)
2 Directly complete the full path of the command exec('/usr/sbin',$output); (recommended)

The above is the detailed content of Solution to the problem that the exec() function in PHP fails to execute system commands. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete