Skip to content

Instantly share code, notes, and snippets.

@kontoulis
Last active February 10, 2021 11:04
Show Gist options
  • Save kontoulis/de34f015f448654139dfb3a16c477fe8 to your computer and use it in GitHub Desktop.
Save kontoulis/de34f015f448654139dfb3a16c477fe8 to your computer and use it in GitHub Desktop.
A small php script you can use to add quickly a new vhost in apache
#!/usr/bin/php
<?php
if (posix_getuid() !== 0){
die("Please run this as root/sudo\n");
}
$apacheTemplate = "<VirtualHost *:port>
ServerAdmin server_admin
ServerName server_name
ServerAlias server_alias
DocumentRoot document_root
<Directory document_root/>
Options Indexes FollowSymLinks MultiViews
AllowOverride All
Require all granted
</Directory>
</VirtualHost>";
$values = [
"server_name" => null,
"server_alias" => null,
"document_root" => null,
"port" => null,
"server_admin" => null
];
foreach($values as $k => &$v){
while(is_null($v)) {
if($k == "port"){
$v = 80;
}elseif ($k == "server_admin"){
$v = "admin@example.com";
}elseif($k == "server_alias"){
$v = $values["server_name"];
}
$input = readline("Enter " . str_replace("_", " ", ucfirst($k)) . " ".($k == "document_root" ? "(expands symbolic links)" :"").(!is_null($v) ? "(optional, defaults to $v)" :"").": ");
if(!empty($input)){
if($k == "document_root" && strpos($input,".") === 0){
$input = realpath($input);
}
$v = $input;
}
}
}
if(is_null($values["server_alias"]) && !is_null($values["server_name"])){
$values['server_alias'] = $values['server_name'];
}
if(in_array(null, $values)){
die("Please add all the required options\n");
}
$config = str_replace(array_keys($values), array_values($values), $apacheTemplate);
if(file_exists("/etc/apache2/sites-available/{$values['server_name']}.conf")){
die("/etc/apache2/sites-available/{$values['server_name']}.conf already exists");
}
file_put_contents("/etc/apache2/sites-available/{$values['server_name']}.conf", $config);
$output = shell_exec("a2ensite {$values['server_name']} && service apache2 reload");
echo "\n$output\n";
file_put_contents("/etc/hosts","\n127.0.0.1\t{$values["server_name"]}", FILE_APPEND);
exit("Website is ready! Visit http://".$values['server_name']."\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment