So I am trying to automatically create subdomains for my website using PHP. I tried the following code but it gives me a 301
error and redirects me to my cPanel login
function createDomain($domain) {
// your cPanel username
$cpanel_user = 'User';
// your cPanel password
$cpanel_pass = 'Pass';
// your cPanel skin
$cpanel_skin = 'paper_lantern';
// your cPanel domain
$cpanel_host = 'example.com';
// subdomain name
$subdomain = $domain;
// directory - defaults to public_html/subdomain_name
$dir = 'public_html/user_site';
// create the subdomain
$sock = fsockopen($cpanel_host,2083);
if(!$sock) {
print('Socket error');
exit();
}
$pass = base64_encode("$cpanel_user:$cpanel_pass");
$in = "GET /frontend/$cpanel_skin/subdomain/doadddomain.html?rootdomain=$cpanel_host&domain=$subdomain&dir=$dirrn";
$in .= "HTTP/1.0rn";
$in .= "Host:$cpanel_hostrn";
$in .= "Authorization: Basic $passrn";
$in .= "rn";
fputs($sock, $in);
while (!feof($sock)) {
$result .= fgets ($sock,128);
}
fclose($sock);
return $result;
}
Like I said it gives me a 301
error and redirects to example.com:2083
instead of just doing it in the code and not having me login to the cPanel manually. Any help would be greatly appreciated!
3
Answers
ANSWER: After fiddling with my code I realized that port
2082
and port2083
are the same except that2082
has nohttps://
so I changed the port to2082
and it worked!CODE:
API 1 is now dead. Also passing your cpanel password through a non-secure connection (ie port 2082 instead of 2083) is a very bad idea. Next thing you know someone will have hijacked your cpanel account!
However, combining the codes given here for authentication and here for adding a subdomain, gives us the following script which seems to work just fine:
The result should be something like this:
To delete the subdomain, run this query through the above script:
And to delete the directory, run this:
Noel’s answer from 2018 more than likely won’t work anymore, but if you’ve come here looking for how to use the Cpanel API to add a subdomain, start at this link to see the arguments accepted for the Cpanel API Ver 2 for the SubDomain module
addsubdomain
.Below is an example that worked perfectly well for me.
Note that if you want to see what Cpanel is returning as a response for
$result
, then placeprint $result;
aftercurl_close($curl);