Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Subdomain PHP

Okay, this might have been answered before but apparently up until now I still haven't found the answer.

You may notice there are some websites that may allow users to register to instantly get a subdomain of their own in the website.

For example, the domain is www.domain.com. If I register a new user as henson, I will get my own page in the website, ex: www.henson.domain.com (not sure if the www part is necessary) So if a user open www.henson.domain.com, it will actually open www.domain.com?owner=henson

Can I do this using only htaccess? Because I read somewhere that this also needs manual creation of subdomains in cpanel (which defeats the purpose of the website).

Oh, the website is coded with flat PHP, so no MVC frameworks. IF someone knows how to do this easily with frameworks (preferably CodeIgniter), be welcome to answer.

Thanks for the answer.

like image 711
Henson Avatar asked Oct 20 '10 09:10

Henson


2 Answers

You cant in htaccess, you must setup a wild card virtual host and rewrite it to the URL/directory you require. See http://blog.orite.com.au/web_development/2009-01-22/setting-up-wildcard-virtual-hosts-for-web-development-environment/ for more info

like image 126
Petah Avatar answered Oct 19 '22 10:10

Petah


If you have CPANEL on your server, there is an XMLAPI which allows you to dynamically creates subdomains through PHP.

Yes, dynamically, not manually. I just spent the last 2 days on this (dynamic creation of everything from subdomains to email accnts to addon domains and sql dbs, users....everything), and cpanel API handles it all, cleanly. So take a while and figure it out.

Download the XMLAPI at the first link on this page: http://forums.cpanel.net/f42/xml-api-php-class-version-1-0-a-136449.html. The file xmlapi.php is the only one you need on your server.

That forum page is a nightmarish graveyard of half working examples written by very advanced and/or very hacky coders with no clear starting point.

Here is a basic script in PHP to add subdomains, replace the caps w your personal values. This took me quite a while to get right. Best of luck! Next steps, hit that forum link and read all the other API1 and API2 functions!

include("PATH_TO_THE_DOWNLOADED_xmlapi.php");

    $ip = "YOUR_IP_ADDRESS";
$root_pass = "ROOT_CPANEL_PASSWORD!";


$xmlapi = new xmlapi($ip);
$xmlapi->password_auth("root",$root_pass);

$account = "YOUR_CPANEL_MAIN_ACCNT_NAME";


print $xmlapi->api2_query($account, 'SubDomain','addsubdomain', array(dir=>"public_html/NAME_OF_SUBDOMAIN", domain=>"NAME_OF_SUBDOMAIN", rootdomain=>"MAIN_DOMAIN.com") );
like image 25
Phil Avatar answered Oct 19 '22 10:10

Phil