我正在开发 laravel,需要使用 laravel 动态创建子域,而不需要进行 cPanel 或服务器设置。
在这里说我有 abc.xyz.com 并且我想创建 {subdomain}.abc.xyz.com 。子域名将动态变化。
要访问,我在 laravel 路由中使用以下代码。
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';
});
我也搜索过,但只找到了 .htaccess 的方法。
这是执行此操作的唯一方法还是还有其他方法可以动态创建子域。
前段时间我想在我的项目中动态创建一个子域。我正在使用核心 PHP 进行编码。我认为这可能对您或其他人有帮助。 这是我的解决方案。
然后第 2 步:在项目的主目录中,我使用以下代码创建了 createSubDomain.php 文件:
$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;
在网络服务器上运行此代码后,您可以检查子域部分,是否创建了一个新的子域,如下图所示:
您可以使用
/execute/SubDomain/addsubdomain
以编程方式创建子域。查看此cPanel文档以获取更多信息。
function create_subdomain($subDomain,$cPanelUser,$cPanelPass,$rootDomain) {
$subdomainRequest = "/execute/SubDomain/addsubdomain?domain=" . $subDomain . "&rootdomain=" . $rootDomain . "&dir=public_html/" . $subDomain . ".". $rootDomain;
$openSocket = fsockopen('localhost',2082);
if(!$openSocket) { return "Socket error";exit();}
$authString = $cPanelUser . ":" . $cPanelPass;
$authPass = base64_encode($authString);
$buildHeaders = "GET " . $subdomainRequest."\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 . "/";
return "Created subdomain $newDomain";
}
echo create_subdomain("Subdomain","cPanel-Username","cPanel-Password","Root-Domain");