How to call shell script from php that requires SUDO?
Edit the sudoers file (with visudo
) and add a rule that allows the web server user to run the command without a password. For example:
www-data ALL=NOPASSWD: /path/to/script
how to run php exec with sudo on live server
I don't recommend running the script as sudo
. A better alternative is to give permission to the web server (www-data
user) to write to the ../../merchants
directory.
First add yourself to the www-data
group by running the command below.
usermod -a -G www-data <your-username>
Then give the ownership of the merchants
folder to the www-data
group using the command below.
chgrp www-data merchants
Lastly give the correct permissions to the merchants
folder using the command below.
chmod g+rwxs merchants
Hope this helps you solve your issue.
EDIT
On CentOS, you should use apache
instead of www-data
.
Run PHP shell_exec() like root user
Executing commands as root via PHP will leave yourself wide open to all sorts of malicious hackery.
Have a look at the "sudo" documentation.
You should be able to set up all the commands you need as "sudo"able scripts. It is much better to write specific scripts with limited functions than to expose the underlying priviledged command.
As in:
exec ('sudo getCurrentUser.sh')
First, you need to add the user that PHP is using to run (most of the time it is www-data
) to the sudo group if it is not already assigned.
Then, in your php file:
use sudo -S, so you can pass the password via echo
$exec = "echo your_passwd | /usr/bin/sudo -S your command";
exec($exec,$out,$rcode);
if you have trouble with the paths - use
"bash -lc 'echo your_passwd | /usr/bin/sudo -S your command'"
so you get a new bash that acts like a login shell and has the paths set
Related Topics
Get $_Post from Multiple Checkboxes
Convert a PHP Object to an Associative Array
How to Get a Form Input Array into a PHP Array
Pdoexception Sqlstate[Hy000] [2002] No Such File or Directory
How to Decode Unicode Escape Sequences Like "\U00Ed" to Proper Utf-8 Encoded Characters
In PHP, What Is a Closure and Why Does It Use the "Use" Identifier
Escaping Quotation Marks in PHP
How to Search by Key=≫Value in a Multidimensional Array in PHP
Sending Email With PHP from an Smtp Server
How to Reindex an Array in PHP But With Indexes Starting from 1
Startswith() and Endswith() Functions in PHP
Fatal Error: Maximum Execution Time of 30 Seconds Exceeded
How to Create a Pdo Parameterized Query With a Like Statement