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 : 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/script.sh
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/script.sh');
You can put anything you need that should run as root into this script. For example, your
script.sh could look like that:
You can also pass additional parameters into the script:
echo shell_exec('sudo /path/to/the/script.sh google.com');
/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.