How to let PHP to create subdomain automatically for each user?

Viewed 143435

How do I create subdomain like http://user.mywebsite.example? 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?

12 Answers

You're looking to create a custom A record.

I'm pretty sure that you can use wildcards when specifying A records which would let you do something like this:

*.mywebsite.example       IN  A       127.0.0.1

127.0.0.1 would be the IP address of your webserver. The method of actually adding the record will depend on your host.


Then you need to configure your web-server to serve all subdomains.

  • Nginx: server_name .mywebsite.example
  • Apache: ServerAlias *.mywebsite.example

Regarding .htaccess, you don't really need any rewrite rules. The HTTP_HOST header is available in PHP as well, so you can get it already, like

$username = strtok($_SERVER['HTTP_HOST'], ".");

If you don't have access to DNS/web-server config, doing it like http://mywebsite.example/user would be a lot easier to set up if it's an option.

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.example/album/Dance/now

I get back

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

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

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

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][1].

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. [1]: http://httpd.apache.org/docs/2.0/vhosts/mass.html

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.

Create Dynamic Subdomains using PHP and .htaccess

#(1) Root .htaccess This file is redirection http://www.yourwebsite.example to http://yourwebsite.example for home page use. All of the subdomain redirection to yourwebsite_folder

RewriteEngine On

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

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

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

#(2) Inside Folder .htaccess This file is rewriting the subdomain URLs.

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

Options +FollowSymLinks
RewriteEngine On

RewriteBase /

RewriteRule ^([aA-zZ])$ index.php?siteName=$1
RewriteCond %{HTTP_HOST} ^(^.*)\.yourwebsite.example
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.example/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.example
RewriteRule (.*) http://yourwebsite.example/$1 [R=301,L]

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

You can accomplish this via two steps.

  1. Setup wildcard subdomain
  2. Get the subdomain entered by user
  3. Validate the subdomain

1. Setup wildcard subdomain

This might vary depending on your hosting provider. I use Namecheap.com, and the process was as simple as follows creating a sub domain in namecheap

  • go to cPanel
  • go to sub domains
  • enter "*" as the value of subdomain

Now every time you enter a random string before your domain name, it will direct to the wildcard sub domain. You can modify the contents of this wildcard subdomain.

2. Get the subdomain entered by user

You can now add a php file in the wildcard directory in file manager.

<?php
    
$link = $_SERVER['HTTP_HOST'];
$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
?>

<!DOCTYPE html>
<html lang="en">
    
  <head>
      
    <title>Wildcard Subdomain</title>
    
  </head>
  
  <body>
      <h1>The visitor went to 
      <?php 
        
        echo "<br>";
        
        print("link is: ".$link);
        
        print("<br><br>");
        
        echo "actual file: ".$actual_link;
      ?> 
      </h1>
        
  </body>
</html>

3. Validate the subdomain

You might want to validate the sub domain to check if there is some user linked to it. This can be done with a check to a database.

Related