Execute Sudo Commands as Root in PHP on CentOS

Published on May 21, 2019

Today we are going to see how to run Linux server commands as root using PHP script. We can run commands easily using shell_exec()function. We can also run using exec().

From StackOverflow: shell_exec returns all of the output streams as a string. exec returns the last line of the output by default, but can provide all output as an array specified as the second parameter.

Enable shell_exec() Function

By default shell_exec() function is disabled. First, we need to enable this. We have edit php.ini file. Let’s find out the php.ini file location by typing this command:

php --ini

If we run this command, the output should look like:

Configuration File (php.ini) Path: /etc
Loaded Configuration File: /etc/php.ini

Now open php.ini file and you can see disable_functions like this:

disable_functions=show_source, system, shell_exec, exec

Let’s remove shell_exec and exec from the list. Then it should look like:

disable_functions=show_source, system

Restart the web server:

# Apache
sudo systemctl restart httpd
# PHP-FPM
sudo /etc/init.d/php-fpm restart

We have enabled the shell_exec function.

Set Permission to Execute Command in PHP File

We need to run:

visudo

I’m going to set permission for the username www-data to execute all commands in PHP file. Add this line to the opened file:

www-data ALL=NOPASSWD: ALL

We have given full access to run commands in PHP. You can give a specific function to work in a PHP file. This is an example of this:

www-data ALL=NOPASSWD: /usr/bin/service

You need to replace www-data with your username. Now save (!wq) the file and try to run Linux command.

Run Commands in PHP

Let’s try to run a command as root:

<?php
// check shell_exec is installed
if(!function_exists('shell_exec')) {
    echo "shell_exec is'nt enabled";
}

// run a command
$output = shell_exec('sudo php -v');
echo "<pre>$output</pre>";

The output:

PHP 7.2.8 (cli) (built: Jul 17 2018 09:50:46) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies

Comments (0)