Actually, you *CAN* use php to do this, but I wouldn't recommend it. I wrote a script to do this for a former project I was working on, and for the most part it worked fine (because I was the only one who used it) but there were still some rough spots (See problem list below).
Make sure your domain is wildcarded (Accepts requests to any subdomain, regardless of whether it actually exists or not)
create a blank file, called subdomains.conf (or whatever you like) but make sure you don't put it in a web accessible directory (Your home dir should be fine), then chown it to the user that apache runs as (usually apache or www) so it's writable by php.
In you main httpd.conf, add the following line at the bottom:
Include /path/to/subdomains.conf
In your script that you want to create the subdomain, add code to create the subdirectory for the subdomain, and to add the subdomain vhost entry to subdomains.conf ($name is the subdomain you are going to create):
@mkdir ( "/path/to/subdirectory/".$name );
$vhost = "<VirtualHost *:80>
ServerAdmin <!-- e -->yourname@yourserver.com<!-- e -->
DocumentRoot /path/to/subdirectory/".$name."
ServerName ".$name.".yourserver.com
ErrorLog /path/to/logs/".$name."_error_log
</VirtualHost>
";
$fo = fopen ( "/path/to/subdomains.conf", "a" );
$fw = fwrite ( $fo, $vhost );
fclose ( $fo );
- @mkdir ( "/path/to/subdirectory/".$name );
- $vhost = "<VirtualHost *:80>
- ServerAdmin <!-- e -->yourname@yourserver.com<!-- e -->
- DocumentRoot /path/to/subdirectory/".$name."
- ServerName ".$name.".yourserver.com
- ErrorLog /path/to/logs/".$name."_error_log
- </VirtualHost>
- ";
- $fo = fopen ( "/path/to/subdomains.conf", "a" );
- $fw = fwrite ( $fo, $vhost );
- fclose ( $fo );
-
There are several potential problems with this approach though:
1. Apache will need to be restarted after each new subdomain is created. You can use php's execute or system commands to run apachectl restart, but this can cause problems if there will be several people creating subdomains. If one person creates a subdomain and submits it, the server will restart and may interrupt someone else creating a subdomain.
2. If something goes wrong with writing the subdomains.conf file, ALL of the subdomains could be lost.
3. You will need to be very strict with your subdomain naming rules, and filter them heavily, and prevent duplicates. If you don't do this, apache could fail to restart and then your whole server will be down.
4. Apache could fail to restart for some unforseeable reason.
A simpler approach would be to wildcard your domain so it responds to any subdomain, then use a header php script to read the $_HOST var, split it up on period (.) determine what the subdomain is and serve the users data that way.