Run PHP or Bash script as root


Sometimes you need to run your PHP or Bash (or whatever) script as root user. For example, you need root privileges to deal with raw sockets, or else it won't work and you'll get the following warning:

socket_create(): Unable to create socket [1]: Operation not permitted

To overcome that you've could run your web server as root user, which is the most terrible idea you've could come up with. You also could run your script with sudo command and pass there your root password. Not as terrible as before, but still, not the best.

The better way is to use sudoers. This is a special configuration file which is usually can be found at /etc/sudoers and which lets you to specify some particular scripts that should be able to run as root without prompting for the root password.

Open this file and add the follwing line:

nginx ALL (root) NOPASSWD: /path/to/the/

Don't forget to put a new line at the end of the file or it will generate an error. Now your PHP-FPM service can run this script as root without root password:

echo shell_exec('sudo /path/to/the/');

You can put anything you need that should run as root into this script. For example, your could look like that:

/usr/bin/php /path/to/php/dealing_with_raw_sockets.php

You can also pass additional parameters into the script:

echo shell_exec('sudo /path/to/the/');
/usr/bin/php /path/to/php/dealing_with_raw_sockets.php $1

I don't think I need to remind you that running whatever with root privileges should be done extremely carefully due to security reasons.

Share this page:

See also how to:

How to install PHP FastCGI Process Manager (FPM) on CentOS 7
A very simple steps to install PHP 7 on CentOS 7
How to extract files from zip archive in Linux command line
How to extract files from different tar archives in Linux command line
How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP