<?php
function isPackageInstalled($package) {
$status = shell_exec("dpkg -s $package 2>&1");
return strpos($status, 'install ok installed') !== false;
}
function installPackage($package) {
echo "Installing $package...\n";
shell_exec("sudo apt-get update");
shell_exec("sudo apt-get install -y $package");
}
function isCommandAvailable($command) {
$status = shell_exec("which $command 2>&1");
return !empty($status);
}
$requiredPackages = ['apache2', 'php'];
foreach ($requiredPackages as $package) {
if (!isPackageInstalled($package)) {
installPackage($package);
} else {
echo "$package is already installed.\n";
}
}
if (!isCommandAvailable('a2ensite')) {
die("The 'a2ensite' command is not available. Ensure that Apache is installed correctly.\n");
}
echo "Enter the folder name (e.g., my_website): ";
$folderName = trim(fgets(STDIN));
echo "Enter the path for the web files (e.g., /var/www/): ";
$documentRootBase = trim(fgets(STDIN));
echo "Enter the port number for the virtual host (e.g., 8080): ";
$port = trim(fgets(STDIN));
if (!$folderName || !$documentRootBase || !$port) {
die("All inputs are required. Exiting...\n");
}
$documentRoot = rtrim($documentRootBase, '/') . '/' . $folderName;
if (!is_dir($documentRoot)) {
mkdir($documentRoot, 0755, true);
mkdir("$documentRoot/public_html", 0755, true);
file_put_contents("$documentRoot/public_html/index.php", "<?php echo 'Hello, $folderName!'; ?>");
shell_exec("sudo chown -R www-data:www-data $documentRoot");
shell_exec("sudo chmod -R 775 $documentRoot");
shell_exec("sudo chmod g+s $documentRoot");
}
$vhostConfig = "
<VirtualHost *:$port>
ServerAdmin webmaster@$folderName
DocumentRoot $documentRoot/public_html
ErrorLog \${APACHE_LOG_DIR}/$folderName-error.log
CustomLog \${APACHE_LOG_DIR}/$folderName-access.log combined
<Directory $documentRoot/public_html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
";
$configFile = "/etc/apache2/sites-available/$folderName.conf";
file_put_contents($configFile, $vhostConfig);
$portsConf = '/etc/apache2/ports.conf';
$portsConfContents = file_get_contents($portsConf);
if (strpos($portsConfContents, "Listen $port") === false) {
echo "Adding port $port to /etc/apache2/ports.conf...\n";
file_put_contents($portsConf, "\nListen $port\n", FILE_APPEND);
} else {
echo "Port $port is already configured in /etc/apache2/ports.conf.\n";
}
shell_exec("sudo a2ensite $folderName.conf");
shell_exec("sudo systemctl reload apache2");
echo "Virtual host for $folderName created, port $port added to ports.conf, and Apache reloaded.\n";
?>