Skip to content
PHP Logo

Is it possible to set up a virtual host for each user with different user IDs in PHP?

Setting up a virtual host for each user with different user IDs in PHP can be achieved by dynamically creating virtual host configurations for each user. This can be done by programmatically generating Apache virtual host configuration files based on user IDs and then restarting the Apache server to apply the changes.

php
<?php

// Define the base directory for virtual hosts
$baseDir = '/etc/apache2/sites-available/';

// Array of user IDs
$userIDs = [1, 2, 3];

// Loop through user IDs to create virtual host configurations
foreach ($userIDs as $userID) {
    $config = "
    <VirtualHost *:80>
        ServerName user$userID.example.com
        DocumentRoot /var/www/user$userID
        ErrorLog \${APACHE_LOG_DIR}/error.log
        CustomLog \${APACHE_LOG_DIR}/access.log combined
    </VirtualHost>
    ";
    
    file_put_contents($baseDir . "user$userID.conf", $config);
}

// Restart Apache server to apply changes
exec('sudo service apache2 restart');

?>