How to create subdomain programatically using PHP

DNS follows a tree structure with each RR-node(resource record) on the tree being a domain name. A subdomain is part of the domain. For instance, if a website named, then sub-domain of this website would probably look like A subdomain is helpful when you create content which is different from the main domain. So when search engines crawl a subdomain and domain they consider it as two different websites rather than one. To create a subdomain using PHP dynamically here is the small code snippet:

  1. Port number 2082 must be open for cPanel Installation.
  2.  Get cPanel skin name. This you can find out form the URL after logging in to cPanel. let’s say URL looks like this  Then paper_lantern is the skin name.
  3. Here is the snippet:


$cpanel_user = “cpanel_username”;

// your cPanel password. Replace ‘cpanel_password; with your cPanel password.

$cpanel_pass = “cpanel_password”;

// your cPanel skin. Replace x2 with your cpanel skin in use.

$cpanel_skin = “paper_lantern”;

// your cPanel domain

$cpanel_host = “”;
$subdomain = “testing”;

function create_subdomain($subDomain,$cPanelUser,$cPanelPass,$rootDomain) {

// $buildRequest = “/frontend/x3/subdomain/doadddomain.html?rootdomain=” . $rootDomain . “&domain=” . $subDomain;

$buildRequest = “/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=” . $rootDomain . “&domain=” . $subDomain . “&dir=public_html/subdomains/” . $subDomain;

$openSocket = fsockopen(‘localhost’,2082);
if(!$openSocket) {
return “Socket error”;

$authString = $cPanelUser . “:” . $cPanelPass;
$authPass = base64_encode($authString);
$buildHeaders = “GET ” . $buildRequest .”\r\n”;
$buildHeaders .= “HTTP/1.0\r\n”;
$buildHeaders .= “Host:localhost\r\n”;
$buildHeaders .= “Authorization: Basic ” . $authPass . “\r\n”;
$buildHeaders .= “\r\n”;

fputs($openSocket, $buildHeaders);
while(!feof($openSocket)) {

$newDomain = “http://” . $subDomain . “.” . $rootDomain . “/”;

echo “Created subdomain $newDomain”;

return $newDomain;

$domain = create_subdomain($subdomain, $cpanel_user, $cpanel_pass, $cpanel_host);

echo “<br/>”;
echo “<a href=”+$domain + “>Domain </a>”;



Thanks for dropping by!! Feel free to comment to this post or you can also drop me an email at [email protected].