Last Updated: September 09, 2019
·
824
· jhernandis

newvhost.php

This is the scritpt that I use to add new vhost to XAMPP

<?php 
$result = 0;
if ($_POST['domain'] != '') {

    $domain = $_POST['domain'];
    $path_logs = 'c:/xampp/apache/logs';
    $path_web = 'c:/xampp/htdocs/%domain%/web'; 
    $file_vhosts = 'c:/xampp/apache/conf/extra/httpd-vhosts.conf';
    $vhost_template = "

## %domain% ------------------------------------------------------- 
<VirtualHost %domain%:80>
    DocumentRoot %path_web%
    ServerName %domain%
    ServerAlias www.%domain%
    ErrorLog %path_logs%/%domain%.error.log
    CustomLog %path_logs%/%domain%.access.log common
    <Directory \"%path_web%\">
        Options Indexes Includes execCGI FollowSymLinks
        AllowOverride All
        Order Allow,Deny
        Allow From All
    </Directory>
</VirtualHost>
";

    $path_web = str_replace('%domain%', $domain, $path_web);

    // List of folders to made
    $mk_dirs = array();
    array_push($mk_dirs, $path_web);
    array_push($mk_dirs, 'c:/xampp/htdocs/%domain%/psd');
    array_push($mk_dirs, 'c:/xampp/htdocs/%domain%/doc');

    // Now we made the folders
    foreach($mk_dirs as $newdir) {
        $newdir = str_replace('%domain%', $domain, $newdir);
        // If the folder does not exists        
        if (!file_exists($newdir)) {
            if (!mkdir($newdir, 0777, true)) { // Really in Windows the 0777  is not necessary
                $result = -2;
                break;
            }
        }       
    }

    // If the folders was made, then add the virtualhost
    if ($result == 0) {
        if ($file = fopen($file_vhosts, 'a')) {
            $tmp = $vhost_template;
            $tmp = str_replace('%domain%', $domain, $tmp);
            $tmp = str_replace('%path_web%', $path_web, $tmp);
            $tmp = str_replace('%path_logs%', $path_logs, $tmp);
            fwrite($file, $tmp, strlen($tmp));
            fclose($file);
            $result = 1;
        } else
            $result = -1;
    }

} 

$msg = '';
switch ($result) { 
    case 1:
        $msg = "<p>Virtual host added successfully. Apache must be restarted.</p>";
        break;
    case -1:
        $msg = "<p style=\"color:red;\">Error: Virtual host cannot be added.<br/>The file '$file_vhosts' cannot be modified</p>";
        break;  
    case -2:
        $msg = "<p style=\"color:red;\">Error: Cannot create the folder '$newdir'</p>";
        break;  
} 
?>

<html>
<head>
<title>Add a new virtualhost</title>
</head>
<body>
<h1>Add a new virtualhost</h1>
<?= $msg; ?>
<form action="creavhost.php" method="post">
Domain (w/o www.): <input name="domain" type="text" size="50" value="domain.local">&nbsp;<input type="submit" value="Submit">
</form>
</body>
</html>