Basically, I want to run below script locally in order start stop restart and get status of service. And it must show output of each command button. I am using php 5.6 in order to run this code.
Below is the code:
<?php
// define cmds
$commands = [
'stop_apache' => [
'description' => 'Stop Apache2',
'cmd' => 'systemctl stop apache2'
],
'restart_apache' => [
'description' => 'Restart Apache2',
'cmd' => 'systemctl restart apache2'
],
'start_apache' => [
'description' => 'Start Apache2',
'cmd' => 'systemctl start apache2'
],
'status_apache' => [
'description' => 'Status Apache2',
'cmd' => 'systemctl status apache2'
],
];
// handle post
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$error = [];
$result = '';
// validate input
if (empty($_POST['service'])) {
$error = [
'service' => 'Service type required!'
];
} elseif (!array_key_exists($_POST['service'], $commands)) {
$error = [
'service' => 'Invalid Service!'
];
}
}
?>
<form action="" method="post">
<?php if (!empty($error)): ?>
<h3>Error</h3>
<pre><?= print_r($error, true) ?></pre>
<?php endif ?>
<?php foreach ($commands as $key => $command): ?>
<button type="submit" name="service" value="<?= $key ?>"><?=
$command['description'] ?></button>
<?php endforeach ?>
</form>
<?php if (!empty($result)): ?>
<pre><?= print_r($result, true) ?></pre>
<?php endif ?>
You are most likely going to encounter permission issues because the web server user
www-data
, will not have permissions to restart the service.So unless you allow that, it's not going to work. The previous code which works is because you are logging in over SSH with root user.
Ok so if you did add allow
www-data
to restart the service, your code would be like the following. By usingexec()
to execute the cmd.You will notice it will fail with
Could not restart service! Status code: 1
- Becausewww-data
wont have permissions. You should read https://serverfault.com/questions/69847/linux-how-to-give-a-user-permission-to-restart-apache on how to fix that, also be aware it opens up the possibility of bad code constantly restarting apache and DOSing.Personally, I would not do it directly as you want to do, but instead set up a task which is run by root user, and you place the operations (restart, stop etc) in a queue to run.
Hope that helps.