Ubuntu 16.04.4下通过PHP重启Apache失败求助
Hey there, let’s dig into why your PHP script isn’t restarting Apache—this is a super common issue tied to system permissions, not just file access rights. Let’s break down the most likely causes and fixes:
1. The PHP runtime user lacks sudo permissions (the #1 culprit)
PHP runs under Apache’s default user, www-data, which has almost no system-level privileges by default. Setting your script to 777 doesn’t change this—file permissions control who can read/write the script, not what system commands the user can run.
Fix steps:
- Open the sudoers file safely (never edit it directly with a regular text editor):
sudo visudo - Add this line at the bottom to let
www-datarestart Apache without entering a password:www-data ALL=(ALL) NOPASSWD: /usr/sbin/service apache2 restart - Save and exit (in nano, that’s
Ctrl+O,Enter,Ctrl+X).
2. You’re not capturing error output (so you think there’s no error)
By default, PHP’s exec() or system() functions only capture standard output (STDOUT), not error messages (STDERR). That’s why you’re seeing "no errors"—they’re just hidden.
Fix with debug code:
Use this snippet to catch all output, including errors:
<?php $output = []; $return_code = 0; // 2>&1 redirects STDERR to STDOUT so we can see errors exec('sudo /usr/sbin/service apache2 restart 2>&1', $output, $return_code); echo "Return Code: " . $return_code . "<br>"; echo "Full Output:<br>"; print_r($output); ?>
A return code of 0 means success; anything else is an error. The output will tell you exactly what’s wrong (e.g., "permission denied").
3. PHP’s execution functions are disabled
Check if exec, system, or shell_exec are blocked in your php.ini config.
Fix:
- Open the Apache-specific php.ini file:
sudo nano /etc/php/7.0/apache2/php.ini - Look for the
disable_functionsline. If any of the execution functions are listed, remove them. - Save and restart Apache manually first:
sudo service apache2 restart
4. AppArmor is blocking the command
Ubuntu 16.04 uses AppArmor to restrict what processes can do. It might be preventing www-data from running sudo or service.
Test and fix:
- Temporarily stop AppArmor to test:
sudo systemctl stop apparmor - If your script works now, you’ll need to create a custom AppArmor profile to allow the restart command (for production) or leave it disabled (only for testing environments).
5. Stop using 777 permissions—it’s useless and dangerous
Setting your script to 777 doesn’t help with system command permissions, and it lets any user on the server modify your script. Revert it to a safe permission level instead:
sudo chmod 644 /path/to/your/script.php
Quick test to confirm permissions
Run this command as the www-data user to simulate what PHP is doing:
sudo -u www-data sudo /usr/sbin/service apache2 restart
If you get an error here, that’s exactly what PHP is hitting—fix that first before troubleshooting the script.
内容的提问来源于stack exchange,提问作者Petey Howell

