How can I create a PHP script for installing apache2 ?
I'd like to also see the installed version after completion.
Here's what I tried:
<?php
if (!empty($_GET['act'])) {
$output = shell_exec ('apt install nodejs');
echo "<pre>$output</pre>";
} else {
//$output = shell_exec('nodejs -v');
//echo "<pre>$output</pre>";
?>
<form action="script.php" method="get">
<input type="hidden" name="act" value="run">
<input type="submit" value="check version">
</form>
?php
}
?>
I want to throw light on multiple issues your script has. First of all, you have lots of syntax errors in your script.
1: For Instance, You haven't closed else
part of your condition using }
. So, Your browser will show something like localhost is currently unable to handle this request.
.
2: Now comes the other thing, Last 3 lines of your script are completely un-necessary, it won't cause errors but it will show up in output which may alter the way you think what error is.
3: You are not getting output because you don't have 2>&1
at the end of your command. Once you add it at the end of your command, you will start getting permission error just like this.
WARNING: apt does not have a stable CLI interface. Use with caution in scripts.
E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied)
E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root?
Now, this error means that you don't have enough permissions to run the command to install something on your machine. There are multiple ways you can solve this permission issue. If you are running your script as www-data
, Add the user to sudo
group using the following command.
usermod -aG sudo www-data
Once you add the user to the group, you can run commands with sudo
and you can run this script perfectly. Here is how the final script should like after solving the permission issues first.
<?php
if (!empty($_GET['act'])) {
$output = shell_exec('sudo apt install nodejs 2>&1');
echo "<pre>$output</pre>";
} else {
$output = shell_exec('nodejs -v');
echo "<pre>$output</pre>";
}
?>
<form action="so1.php" method="get">
<input type="hidden" name="act" value="run">
<input type="submit" value="check version">
</form>
So, this is how you can make your script execute commands to install packages. Let me know if you have more questions regarding this.
UPDATE: I know executing a script with sudo
is "Harmful" and "Not recommended". But It's a way to make this script work. And, If you want to install a package that is bigger in size, add -y
flag at the end of your command just after nodejs
to make pre-select the choice to install or not-install a package.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.