Home > Backend Development > PHP Tutorial > 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

不言
Release: 2023-04-05 08:54:01
forward
8276 people have browsed it

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 和此变量,命令执行后的返回状态会被写入到此变量
Copy after login

2. Example

exec("ping www.baidu.com", $output);
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template