Using cPanel API to create mySQL database and user in PHP - php

I am trying to create a mysql user and assign it to the created database.
I have tried setting $db_host as IP address, FQD, localhost (since I am running from the same server) etc. All of these has no success.
Any advice on what I'm doing wrong? (xmlapi.php is being incuded fine)
include("xmlapi.php");
$db_host = "usingfullyqualifieddomain";
$cpuser = "myuser";
$cppass = "mypass";
$xmlapi = new xmlapi($db_host);
$xmlapi->set_port(2083);
$xmlapi->password_auth($cpuser,$cppass);
$xmlapi->set_debug(1);
//create database
print $xmlapi->api1_query($cpuser, "Mysql", "adddb", 'myDatabaseName');
//create user
print $xmlapi->api1_query($cpuser, "Mysql", "adduser", array('user' => 'myDBUser','pass'=>'myDBPwd'));

The error is probably related to the way you're making your first service call, to create the database. Here is how I do it, on CPanel 11:
$auth_user = 'XXXXXX';
$auth_pass = 'XXXXX';
$server = 'XXXXXXXX.com';
$json_client = new \xmlapi($server);
$json_client->set_output('json');
$json_client->set_port(2083);
$json_client->password_auth($auth_user, $auth_pass);
$json_client->set_debug(1);
# Create Database
$result = $json_client->api1_query( $auth_user, 'Mysql', 'adddb', array($shop->alias));
var_dump($result);
Note that the fourth parameter should be an array with the parameters, and not a string as you are doing it.
Also notice that the print on the api call result is not very useful for debugging. Try var_dump'ing it, as it will show you some more interesting information to work on.

currently, cpanel support the cpanel json api..
here you can use this code ..
this worked for me well
<?php
$cpanelusername = "cpanelusername";
$cpanelpassword = "cpanelpassword";
$domain = 'mydomain.com';
$query = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_module=Mysql&cpanel_jsonapi_func=adddb&cpanel_jsonapi_apiversion=1&arg-0=DBNAME";
$curl = curl_init(); // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode($cpanelusername.":".$cpanelpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // set the username and password
curl_setopt($curl, CURLOPT_URL, $query); // execute the query
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// log error if curl exec fails
}
curl_close($curl);
print $result;
?>

Related

php header with curl always got UNAUTHORIZED

I want to develop a bridging application to web service. I Tried using the encrypted TIMESTAMP, SIGNATURE, AND AUTHORIZATION code with ARC (google add on for web service) to test if my encryption codes are correct and it worked. In my php script All requirements (parameters) are already provided but I always get Unauthorized access even though the password and username are correct. Please help. i'm using php curl. Thank for your help.
this is my php script :
<?php
$data = "xxx";
$secretKey = "xxx";
$url = "http://someurl";
$nik = "xxx";
date_default_timezone_set('UTC');
$tStamp = strval(time()-strtotime('1970-01-01 00:00:00'));
$signature = hash_hmac('sha256', $data."&".$tStamp, $secretKey, true);
$encodedSignature = base64_encode($signature);
$urlencodedSignature = urlencode($encodedSignature);
$pcareUname = "zzz";
$pcarePWD = "zzz";
$kdAplikasi = "zzz";
$encodedAuthorization = base64_encode($pcareUname.":".$pcarePWD.":".$kdAplikasi);
//showing result from encode
echo "X-cons-id: " .$data;
echo "X-timestamp:" .$tStamp;
echo "X-signature: " .$encodedSignature;
echo "X-authorization: " .$encodedAuthorization";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url.$nik);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"X-cons-id: $data",
"X-timestamp: $tStamp",
"X-signature: $signature",
"X-authorization: Basic $encodedAuthorization"
));
$result = curl_exec($ch);
curl_close($ch);
echo($result);
?>

PHP cPanel Create Subdomain

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=$dir\r\n";
$in .= "HTTP/1.0\r\n";
$in .= "Host:$cpanel_host\r\n";
$in .= "Authorization: Basic $pass\r\n";
$in .= "\r\n";
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!
ANSWER:
After fiddling with my code I realized that port 2082 and port 2083 are the same except that 2082 has no https:// so I changed the port to 2082 and it worked!
CODE:
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,2082);
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=$dir\r\n";
$in .= "HTTP/1.0\r\n";
$in .= "Host:$cpanel_host\r\n";
$in .= "Authorization: Basic $pass\r\n";
$in .= "\r\n";
fputs($sock, $in);
while (!feof($sock)) {
$result .= fgets ($sock,128);
}
fclose($sock);
return $result;
}
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:
<?php
$cpanelsername = "example";
$cpanelpassword = "**********";
$subdomain = 'newsubdomain';
$domain = 'example.com';
$directory = "/public_html/$subdomain"; // A valid directory path, relative to the user's home directory. Or you can use "/$subdomain" depending on how you want to structure your directory tree for all the subdomains.
$query = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_func=addsubdomain&cpanel_jsonapi_module=SubDomain&cpanel_jsonapi_version=2&domain=$subdomain&rootdomain=$domain&dir=$directory";
$curl = curl_init(); // Create Curl Object
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0); // Allow self-signed certs
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0); // Allow certs that do not match the hostname
curl_setopt($curl, CURLOPT_HEADER,0); // Do not include header in output
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1); // Return contents of transfer on curl_exec
$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header); // set the username and password
curl_setopt($curl, CURLOPT_URL, $deletedir); // execute the query
$result = curl_exec($curl);
if ($result == false) {
error_log("curl_exec threw error \"" . curl_error($curl) . "\" for $query");
// log error if curl exec fails
}
curl_close($curl);
print $result;
?>
The result should be something like this:
{"cpanelresult":{"func":"addsubdomain","event":{"result":1},"apiversion":2,"module":"SubDomain","data":[{"reason":"The subdomain “newsubdomain.example.com” has been added.","result":1}],"preevent":{"result":1},"postevent":{"result":1}}}
To delete the subdomain, run this query through the above script:
$deletesub = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_func=delsubdomain&cpanel_jsonapi_module=SubDomain&cpanel_jsonapi_version=2&domain=".$subdomain.'.'.$domain."&dir=$directory"; //Note: To delete the subdomain of an addon domain, separate the subdomain with an underscore (_) instead of a dot (.). For example, use the following format: subdomain_addondomain.tld
And to delete the directory, run this:
$deletedir = "https://$domain:2083/json-api/cpanel?cpanel_jsonapi_module=Fileman&cpanel_jsonapi_func=fileop&op=unlink&sourcefiles=$directory";
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.
$whmusername = "cpanel_username";
$whmpassword = "cpanel_password";
$subdomain = 'newsubdomain';
$cpanel_ip = 'IP_ADDRESS'; //ip of cpanel or your_domain.com
$domain = "your_domain.com";
$query = "https://".$cpanel_ip."2083/json-api/cpanel?cpanel_jsonapi_module=SubDomain&cpanel_jsonapi_func=addsubdomain&cpanel_jsonapi_apiversion=2&dir=/public_html/".$subdomain.".".$domain."/&rootdomain=".$domain."&domain=".$subdomain."";
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,0);
curl_setopt($curl, CURLOPT_HEADER,0);
curl_setopt($curl, CURLOPT_RETURNTRANSFER,1);
$header[0] = "Authorization: Basic " . base64_encode($whmusername.":".$whmpassword) . "\n\r";
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_URL, $query);
$result = curl_exec($curl);
curl_close($curl);
Note that if you want to see what Cpanel is returning as a response for $result, then place print $result; after curl_close($curl);

How to test logstash with PHP script

I just have installed logstash, configured its config file with input, filter and output and finally have run it. Is it possible to test if logstash pushes log data by writing some PHP script? Can someone provide me some php script that can catch log data, sending from logstash?
Run the following to get the list of logs in your elasticsearch index :
$date = date("Y.m.d");
$host = "127.0.0.1";
$port = "9200";
$index = "logstash-".$date;
$type = "*";
$log = array();
$query = '{"query":{"match_all":{}}}';
$curl = curl_init();
if ($curl) {
curl_setopt($curl,CURLOPT_URL, $host."/".$index."/".$type."/_search");
curl_setopt($curl, CURLOPT_PORT, $port);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $query);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
if (curl_errno($curl)) {
echo curl_error($curl); //error
}
curl_close($curl);
if (!$result) {
//error
}
$arr=(json_decode($result, true));
$logs = $arr['hits']['hits'];
// If any logs were found
if (count($logs)>0) {
foreach ($logs as $q) {
// load the data in the $data array
$log[] = $q["_source"];
echo "<pre>";
print_r($log);
echo "</pre>";
}
}
}
?>
Cheers.
Do you have use Elasticsearch to store the log data? After you have store the logs in elasticsearch, you can use restful api to get the logs by php.
You must install Elasticsearch PHP client to communicate with elasticsearch server.

Docusign REST call from CodeIgniter

I'm trying to call the DocuSign REST login information within a CodeIgniter application. The Docusign sample code shows:
// Input your info here:
$integratorKey = '...';
$email = '...#....com';
$password = '...';
$name = 'John Doe';
// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";
/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 200 ) {
echo "error calling webservice, status is:" . $status;
exit(-1);
}
I keep getting a status response of 0. When I echo out the curl all the xml tags have been converted to lowercase (which won't work with Docusign). Has anyone done this call within CodeIgniter? How did you accomplish it? I know my credentials are good because I can do a command line curl and get a response.
I'm not sure what CodeIgniter is doing and why the tags would be converted to lower case but you're right in that DocuSign expects xml tags to begin with a capital letter so that might not work. What you can do, though, is use JSON headers and request bodies instead.
For instance, instead of an XML formatted authentication header like
<DocuSignCredentials>
<Username>username</Username>
<Password>password</Password>
<IntegratorKey>integrator_key</IntegratorKey>
</DocuSignCredentials>
You could use the corresponding JSON auth header like
{
"Username": "username",
"Password": "password",
"IntegratorKey": "integrator_key"
}
The "nodes" still start with a capital but since it's not xml I'm wondering if CodeIgniter maybe leaves it alone. Examples of this can be found at the DocuSign Developer Center on this page.

execute external page while doing some function with php?

hello im trying to create a simple script which will create an account with my dedicated server using WHM
here is the simple code
<?php
// your WHM username
$whm_user = 'root';
// your WHM password
$whm_pass = 'pass';
// your WHM hostname
$whm_host = '10.10.10.10';
// new account domain or subdomain name
$user_domain = 'example.com';
// new account username (8 characters or less)
$user_name = 'example';
// new account password
$user_pass = 'example1245';
// new account contact email
$user_email = 'user#example.net';
// new account plan (must be an existing WHM plan)
$user_plan = 'Gold';
// create the account
$site = "https://{$whm_user}:{$whm_pass}#{$whm_host}:2087/scripts/wwwacct";
$params = "?plan={$user_plan}";
$params .= "&domain={$user_domain}";
$params .= "&username={$user_name}";
$params .= "&password={$user_pass}";
$params .= "&contactemail={$user_email}";
$url = $site.$params;
file_get_contents($url);
?>
this return an error
[function.file-get-contents]: failed to open stream: No error in C:\AppServ\www\cp\create-whm-account.php on line 35
then i tried to use CURL
<?php
// your WHM username
$whm_user = 'root';
// your WHM password
$whm_pass = 'pass';
// your WHM hostname
$whm_host = '10.10.10.10';
// new account domain or subdomain name
$user_domain = 'example.com';
// new account username (8 characters or less)
$user_name = 'example';
// new account password
$user_pass = 'example1245';
// new account contact email
$user_email = 'user#example.net';
// new account plan (must be an existing WHM plan)
$user_plan = 'Gold';
// create the account
$site = "https://{$whm_user}:{$whm_pass}#{$whm_host}:2087/scripts/wwwacct";
$params = "?plan={$user_plan}";
$params .= "&domain={$user_domain}";
$params .= "&username={$user_name}";
$params .= "&password={$user_pass}";
$params .= "&contactemail={$user_email}";
$url = $site.$params;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
?>
it doesn't return any error and doesn't work neither
i don't need to return any output as this will work within another functions so i don't need to show any result just create the account within the background
I noticed that you are requesting a HTTPS URL. Extra CURL flags might be required. Very likely:
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
See also: PHP: Curl to fetch html page from HTTPS

Categories