user3737083
user3737083

Reputation:

How to create subdomain dynamically without going cPanel

I am working on laravel and need to create subdomain using laravel dynamically without going cPanel or server setting.

Say here I have abc.xyz.com and I want create {subdomain}.abc.xyz.com . where subdomain will dynamic.

To access I have Use following code in laravel route.

Route::group(['domain' => 'abc.xyz'], function()
{
    return 'Main page will be loaded';
}); 

Route::group(['domain' => '{subdomain}.abc.xyz'], function()
{
    return 'Subdomain page will be loaded';
});

Also I have searched, but just found only way by .htaccess .

Is it the only way to do this or is there any other ways also to create subdomain dynamically.

Upvotes: 3

Views: 7330

Answers (2)

Amit Mhaske
Amit Mhaske

Reputation: 471

Some time ago I wanted to create a subdomain dynamically in my project. I was coding in Core PHP. I think this could be helpful to you or someone else. Here is my solution.

  1. I created wildcard subdomain as shown by @Rockers Technology in previous answer

enter image description here

Then Step 2: On at Home Directory of my project I created createSubDomain.php file with following code:

$subDomain = "mytestdomain";
    $cPanelUser = 'user_name';
    $cPanelPass = 'password';
    $rootDomain = 'main_domain_name';



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


//$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/" . $subDomain;
$buildRequest = "/frontend/paper_lantern/subdomain/doadddomain.html?rootdomain=" . $rootDomain . "&domain=" . $subDomain . "&dir=public_html/code/";

$openSocket = fsockopen('localhost',2082);
if(!$openSocket) {
    return "Socket error";
    exit();
}

$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)) {
fgets($openSocket,128);
}
fclose($openSocket);

$newDomain = "http://" . $subDomain . "." . $rootDomain . "/";
echo $newDomain;

After running this code on webserver, you can check in subdomain section, that a new subdomain gets created as shown in following picture:

enter image description here

Upvotes: 3

Related Questions