why php command `exec("service apache2 restart");` does't work on ubuntu?

19,695

Solution 1

You need to run :

visudo

check that you have a line like

Host_Alias LOCAL=192.168.0.1 

with your own local IP at the top of the file, then add a line

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

And last in your PHP file :

exec("/usr/bin/sudo /usr/bin/service apache2 restart");

(You are trying to restart apache by web, maybe you don't know webmin interface ? I think there's betters solutions than this sudo way. It's not a good thing to authorize www-data to stop, start (...) all the services. Better explain why you'd like to restart apache ;) )

Solution 2

Services (in the sense of system services, like Apache httpd) can only be manipulated (started, stoppped, restarted) by the root user (UID 0).

Either you run the PHP script in root's context (bad idea) or you use something like sudo to run the commands as super user. This said, there are very serious security implications when running programs with super user privileges, especially if you don't sanitize your inputs properly!

Solution 3

Did you look at the Apache error log like it says? What's in there?

Almost certainly your PHP script is running without sufficient permissions to restart Apache. Which is probably for the best. If you really really need this to work, consider making a setuid root script to invoke from PHP (note that this should not be used in production, and will probably create a security hole).

You could also write a little service which runs as root and accepts commands to restart Apache from your PHP script. That'd be a more "proper" way of doing this, though the task at hand seems itself improper, so I'm not sure you should continue down this path.

Share:
19,695
EBAG
Author by

EBAG

Updated on July 26, 2022

Comments

  • EBAG
    EBAG almost 2 years

    I need to execute some commands on my web server with php configured with apache.

    exec("service apache2 restart", $output);
    print_r($output);
    

    output:

    Array (
        [0] =>  * Restarting web server apache2
        [1] => Action 'start' failed.
        [2] => The Apache error log may have more information.
        [3] =>    ...fail! 
    )
    

    My guess is it's because of permissions of php on my ubuntu! What do you suggest?