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

前端 未结 12 1164
暖寄归人
暖寄归人 2020-11-22 13:43

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 u

12条回答
  •  [愿得一人]
    2020-11-22 14:26

    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 
    

提交回复
热议问题