Solution to PHP not having permission to execute exec command on Linux
Related official references
PHP exec Linux sudoers file Sudo CommandsModifications when running in fastcgi mode
When PHP is running in fastcgi mode, its permissions are inherited from its host program. We take apache as an example to explain. First, we need to find the account under which apache is running, and then use vi or vim to edit the /etc/sudoers file, and add the following reference example to the file. In the following content, first use the ps command to find the apache process httpd, look at the account information on the leftmost side of the returned result, and then edit the sudoers file to add authorization to the apache account.
ps aux | grep httpd
vim /etc/sudoers
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
apache ALL=(ALL) NOPASSWD:ALL
Modifications when running in php-fpm mode
When running in php-fpm mode, it runs as a separate process. So we first find its running account, and then perform authorization operations as above.
ps aux | grep php-fpm
vim /etc/sudoers
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
www ALL=(ALL) NOPASSWD:ALL
Verify that the changes take effect
After the above operations, we have modified the authorization, but it has not yet taken effect. We need to restart the service to make our modification take effect. According to our actual situation, restart the apache or php-fpm service. Then execute the exec command to view the returned result. If the returned result is obtained normally, it is successful.
exec('sudo dmidecode -s system-serial-number', $result);
var_dump($result);