How can one create a subdomain using PHP and Apache on an Ubuntu server?

To create a subdomain using PHP and Apache on an Ubuntu server, you can use the Apache VirtualHost configuration to set up a new subdomain. You will need to create a new VirtualHost file for the subdomain, configure it with the appropriate settings, and then enable the new VirtualHost configuration in Apache.

<?php
// Create a new VirtualHost configuration file for the subdomain
$domain = "subdomain.example.com";
$documentRoot = "/var/www/html/subdomain";

$virtualHostConfig = "
<VirtualHost *:80>
    ServerAdmin webmaster@$domain
    ServerName $domain
    DocumentRoot $documentRoot

    <Directory $documentRoot>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>
";

// Save the VirtualHost configuration to a new file
file_put_contents("/etc/apache2/sites-available/$domain.conf", $virtualHostConfig);

// Enable the new VirtualHost configuration
shell_exec("sudo a2ensite $domain.conf");

// Reload Apache to apply the changes
shell_exec("sudo systemctl reload apache2");
?>