[php] How to let PHP to create subdomain automatically for each user?

How do I create subdomain like http://user.mywebsite.com ? Do i have to access htaccess somehow? Is it actually simply possible to create it via pure php code or I need to use some external script-server side language?

To those who answered: Well, then, should i ask my hosting if they provide some sort of DNS access??

This question is related to php subdomain

The answer is


We setup wildcard DNS like they explained above. So the a record is *.yourname.com

Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.

We use the following code:

$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);

This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.

This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).

We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.


Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.

From the documentation:

#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs

In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.

The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.


Simple PHP solution for subdomains and multi-domain web apps

Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve "example.org"

A record => *.example.org
A record => *.example.net

Step 2. Check uniquity of logins when user registering or changing login. Also, avoid dots in those logins.

Step 3. Then check the query

        // Request was http://qwerty.example.org
        $q = explode('.', $_SERVER['HTTP_HOST']);
        /*
            We get following array
            Array
            (
                [0] => qwerty
                [1] => example
                [2] => org
            )
        */

        // Step 4.
        // If second piece of array exists, request was for 
        // SUBDOMAIN which is stored in zero-piece $q[0]
        // otherwise it was for DOMAIN

        if(isset($q[2])) {
            // Find stuff in database for login $q[0] or here it is "qwerty"
            // Use $q[1] to check which domain is asked if u serve multiple domains
        }

?>

This solution may serve different domains

qwerty.example.org
qwerty.example.net 

johnsmith.somecompany.com
paulsmith.somecompany.com

If you need same nicks on different domains served differently, you may need to store user choise for domain when registering login.

smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith 

Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.

From the documentation:

#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs

In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.

The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.


In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.


I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.


Create Dynamic Subdomains using PHP and Htaccess

(1) Root .htaccess

This file is redirection http://www.yourwebsite.com to http://yourwebsite.com for home page use. All of the subdomain redirection to yourwebsite_folder

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^yourwebsite\.com $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

(2) Inside Folder .htaccess

This file is rewriting the subdomain urls.

http://yourwebsite.com/index.php?siteName=9lessons to http://9lessons.yourwebsite.com

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1

More .htaccess tips: Htaccess File Tutorial and Tips.

index.php

This file contains simple PHP code, using regular expressions validating the subdomain value.

<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
   if($siteNameCheck)
   {
     //Do something. Eg: Connect database and validate the siteName.
   }
   else
  {
    header("Location: http://yourwebsite.com/404.php");
   }
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>

No Subdomain Folder

If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1

You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.


The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:

<VirtualHost 111.22.33.55>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>

However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.


You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.


I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.


I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.


Simple PHP solution for subdomains and multi-domain web apps

Step 1. Provide DNS A record as "*" for domains (or domain) you gonna serve "example.org"

A record => *.example.org
A record => *.example.net

Step 2. Check uniquity of logins when user registering or changing login. Also, avoid dots in those logins.

Step 3. Then check the query

        // Request was http://qwerty.example.org
        $q = explode('.', $_SERVER['HTTP_HOST']);
        /*
            We get following array
            Array
            (
                [0] => qwerty
                [1] => example
                [2] => org
            )
        */

        // Step 4.
        // If second piece of array exists, request was for 
        // SUBDOMAIN which is stored in zero-piece $q[0]
        // otherwise it was for DOMAIN

        if(isset($q[2])) {
            // Find stuff in database for login $q[0] or here it is "qwerty"
            // Use $q[1] to check which domain is asked if u serve multiple domains
        }

?>

This solution may serve different domains

qwerty.example.org
qwerty.example.net 

johnsmith.somecompany.com
paulsmith.somecompany.com

If you need same nicks on different domains served differently, you may need to store user choise for domain when registering login.

smith.example.org // Show info about John Smith
smith.example.net // Show info about Paul Smith 

The feature you are after is called Wildcard Subdomains. It allows you not have to setup DNS for each subdomain, and instead use apache rewrites for the redirection. You can find a nice tutorial here, but there are thousands of tutorials out there. Here is the necessary code from that tutorial:

<VirtualHost 111.22.33.55>
    DocumentRoot /www/subdomain
    ServerName www.domain.tld
    ServerAlias *.domain.tld
</VirtualHost>

However as it required the use of VirtualHosts it must be set in the server's httpd.conf file, instead of a local .htaccess.


This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, create a folder for your subdomain and place the subdomains files.


In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


First, you need to make sure your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *. I also specified a folder called subdomains as the document root for wildcard subdomains. Add this to a .htaccess file in your subdomains folder:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, all you need to do is create a folder in your subdomains folder, then place the subdomain's files in that directory.


This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, create a folder for your subdomain and place the subdomains files.


I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.


In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


We setup wildcard DNS like they explained above. So the a record is *.yourname.com

Then all of the subdomains are actually going to the same place, but PHP treats each subdomain as a different account.

We use the following code:

$url=$_SERVER["REQUEST_URI"];
$account=str_replace(".yourdomain.com","",$url);

This code just sets the $account variable the same as the subdomain. You could then retrieve their files and other information based on their account.

This probably isn't as efficient as the ways they list above, but if you don't have access to BIND and/or limited .htaccess this method should work (as long as your host will setup the wildcard for you).

We actually use this method to connect to the customers database for a multi-company e-commerce application, but it may work for you as well.


You could [potentially] do a rewrite of the URL, but yes: you have to have control of your DNS settings so that when a user is added it gets its own subdomain.


Don't fuss around with .htaccess files when you can use Apache mass virtual hosting.

From the documentation:

#include part of the server name in the filenames VirtualDocumentRoot /www/hosts/%2/docs

In a way it's the reverse of your question: every 'subdomain' is a user. If the user does not exist, you get an 404.

The only drawback is that the environment variable DOCUMENT_ROOT is not correctly set to the used subdirectory, but the default document_root in de htconfig.


Create Dynamic Subdomains using PHP and Htaccess

(1) Root .htaccess

This file is redirection http://www.yourwebsite.com to http://yourwebsite.com for home page use. All of the subdomain redirection to yourwebsite_folder

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^yourwebsite\.com $
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteCond %{REQUEST_URI} !^/yourwebsite_folder/
RewriteRule (.*) /yourwebsite_folder/$1

(2) Inside Folder .htaccess

This file is rewriting the subdomain urls.

http://yourwebsite.com/index.php?siteName=9lessons to http://9lessons.yourwebsite.com

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1

More .htaccess tips: Htaccess File Tutorial and Tips.

index.php

This file contains simple PHP code, using regular expressions validating the subdomain value.

<?php
$siteName='';
if($_GET['siteName'] )
{
$sitePostName=$_GET['siteName'];
$siteNameCheck = preg_match('~^[A-Za-z0-9_]{3,20}$~i', $sitePostName);
   if($siteNameCheck)
   {
     //Do something. Eg: Connect database and validate the siteName.
   }
   else
  {
    header("Location: http://yourwebsite.com/404.php");
   }
}
?>
//HTML Code
<!DOCTYPE html>
<html>
<head>
<title>Project Title</title>
</head>
<body>
<?php if($siteNameCheck) { ?>
//Home Page
<?php } else { ?>
//Redirect to Subdomain Page.
<?php } ?>
</body>
</html>

No Subdomain Folder

If you are using root directory(htdocs/public_html) as a project directory, use this following .htaccess file.

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteCond %{HTTP_HOST} ^www.yourwebsite.com
RewriteRule (.*) http://yourwebsite.com/$1 [R=301,L]

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.com
RewriteRule (.*) index.php?siteName=%1

First, you need to make sure your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named *. I also specified a folder called subdomains as the document root for wildcard subdomains. Add this to a .htaccess file in your subdomains folder:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, all you need to do is create a folder in your subdomains folder, then place the subdomain's files in that directory.


In addition to configuration changes on your WWW server to handle the new subdomain, your code would need to be making changes to your DNS records. So, unless you're running your own BIND (or similar), you'll need to figure out how to access your name server provider's configuration. If they don't offer some sort of API, this might get tricky.

Update: yes, I would check with your registrar if they're also providing the name server service (as is often the case). I've never explored this option before but I suspect most of the consumer registrars do not. I Googled for GoDaddy APIs and GoDaddy DNS APIs but wasn't able to turn anything up, so I guess the best option would be to check out the online help with your provider, and if that doesn't answer the question, get a hold of their support staff.


I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.