I had a need to add several domains to Apache for a client about an hour ago, and instead of copying, pasting, changing, and repeating, I opted to script it. It’s very simple (read: not secure for multiple users in production), but served my needs today beautifully. Feel free to clean it up and use it, change it, whatever.
The primary reason this is added is to show how CLI scripts can be made to wait for and accept user input. Note the use of STDOUT and STDIN in the script. This is something that I’ve found to be quite unfortunately overlooked in a lot of CLI scripts. Using this, you can make a PHP CLI script interactive, instead of requiring arguments to be passed on the command line.
Also, note that this particular script wasn’t needed for user creation, DNS, or anything of the like. Strictly for adding an Apache directive for the domain.
(The code itself is indented, but I’m learning more and more why Philip Olsen scoffed at me for installing Serendipity last year. Eventually my error in judgment shall be rectified.)
if(trim(`whoami`) != 'root') die("You must be root to run this command.\n");
fwrite(STDOUT,"Domain to be added: ");
$domain = trim(fgets(STDIN));
fwrite(STDOUT,"Username to use for this domain: ");
$user = trim(fgets(STDIN));
fwrite(STDOUT,"Group to use for this domain: ");
$group = trim(fgets(STDIN));
fwrite(STDOUT,"Path to use for the web root of this domain: ");
$path = trim(fgets(STDIN));
fwrite(STDOUT,"Server administrator's email address to use: ");
$email = trim(fgets(STDIN));
echo "Writing.... ";
CustomLog logs/$domain-access_log combined
suPHP_AddHandler php5-script .php
suPHP_UserGroup $user $group
fwrite(STDOUT,"Should I restart Apache now for the changes to take effect? (y/N) ");
exec('service httpd restart');
echo "Apache restarted.\n";