Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Say hello to redesigned Cloudways, an empowering Startup Program, enhanced Staging, a new Let’s Encrypt Wildcard SSL certificate feature, and more. READ MORE

How to Manage Cloudways Server Settings Using Cloudways API

Updated on October 25, 2016

7 Min Read
Reading Time: 7 minutes

Cloudways API is specially designed for developers and re-sellers. The main benefit of the API is that third party users could enjoy all the features of the platform through a purpose built UI.

Manage Server Settings Using Cloudways API Banner

In our series of API articles, we have used the Cloudways API for performing operations, such as purging Varnish cache, application management, cloning Github repository, etc. In this tutorial, I will discuss how to manage your Cloudways server settings using Cloudways API. I’ll use Guzzle PHP HTTP Client for handling the requests.

As a prerequisite for this tutorial, install the Guzzle client. If you are not clear about the process, you should check out Create And Delete Applications Via Cloudways API tutorial.

Create a new file in the root folder to begin the process. Name it as CloudwaysAPIClient.php and paste the following code in it.

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

use GuzzleHttp\Exception\RequestException;

use GuzzleHttp\Psr7\Request;

Class CloudwaysAPIClient
{
	private $client = null;
	const API_URL = "https://api.cloudways.com/api/v1";
	var $auth_key;
	var $auth_email;
	var $accessToken;
	public function __construct($email,$key)
	{
		$this->auth_email = $email;
		$this->auth_key = $key;
		$this->client = new Client();
		$this->prepare_access_token();
	}
	public function prepare_access_token()
	{
		try
		{
			$url = self::API_URL . "/oauth/access_token";
			$data = ['email' => $this->auth_email,'api_key' => $this->auth_key];
			$response = $this->client->post($url, ['query' => $data]);
			$result = json_decode($response->getBody()->getContents());
			$this->accessToken = $result->access_token;
		}
		catch (RequestException $e)
		{
			$response = $this->StatusCodeHandling($e);
			return $response;
		}
	}
	public function StatusCodeHandling($e)
	{
		if ($e->getResponse()->getStatusCode() == '400')
		{
			$this->prepare_access_token();
		}
		elseif ($e->getResponse()->getStatusCode() == '422')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '500')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '401')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '403')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '404')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		else
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
	}

public function get_servers()
{
	try
	{
		$url = self::API_URL . "/server";
		$option = array('exceptions' => false);
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->get($url, array('headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}

public function get_servers_settings($server_id)
{
	try
	{
		$url = self::API_URL . "/server/manage/settings";
		$option = array('exceptions' => false);
		$data = ['server_id' => $server_id];
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->get($url, array('query' => $data, 'headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}

public function set_servers_settings($serverid,$datetimezone,$displayerrors,$apc_shmsize,$executionlimit,$memorylimit,$maxinput_vars,$maxinput_time,$modxdebug,$uploadsize)
{
	try
	{
		$url = self::API_URL . "/server/manage/settings";
		$option = array('exceptions' => false);
		$data = [
					'server_id' => $serverid,
					'date_timezone' => $datetimezone,
					'display_errors' => $displayerrors,
					'apc_shm_size' => $apc_shmsize,
					'execution_limit' => $executionlimit,
					'memory_limit' => $memorylimit,
					'max_input_vars' => $maxinput_vars,
					'max_input_time' => $maxinput_time,
					'mod_xdebug' => $modxdebug,
					'upload_size' => $uploadsize
				];
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->post($url, array('query' => $data, 'headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}
}
?>

This code starts with calling vendor/autoload.php and defines Guzzle built-in classes.

require 'vendor/autoload.php';

use GuzzleHttp\Client;

use GuzzleHttp\Exception\RequestException;

use GuzzleHttp\Psr7\Request;

After this, the class CloudwaysAPIClient constructor loads the Guzzle and then prepares the Cloudways API access token. The constructor gets the email and API key and further generates the token using the prepare_access_token() function.

Class CloudwaysAPIClient
{
	private $client = null;
	const API_URL = "https://api.cloudways.com/api/v1";
	var $auth_key;
	var $auth_email;
	var $accessToken;
	public function __construct($email,$key)
	{
		$this->auth_email = $email;
		$this->auth_key = $key;
		$this->client = new Client();
		$this->prepare_access_token();
	}
	public function prepare_access_token()
	{
		try
		{
			$url = self::API_URL . "/oauth/access_token";
			$data = ['email' => $this->auth_email,'api_key' => $this->auth_key];
			$response = $this->client->post($url, ['query' => $data]);
			$result = json_decode($response->getBody()->getContents());
			$this->accessToken = $result->access_token;
		}
		catch (RequestException $e)
		{
			$response = $this->StatusCodeHandling($e);
			return $response;
		}
	}

Next, we have the StatusCodeHandling() function for handling most of the status codes generated by the Cloudways API.

public function StatusCodeHandling($e)
	{
		if ($e->getResponse()->getStatusCode() == '400')
		{
			$this->prepare_access_token();
		}
		elseif ($e->getResponse()->getStatusCode() == '422')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '500')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '401')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '403')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '404')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		else
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
	}

Next are the functions that get the server and server settings using Cloudways API. The get_servers() function provides you the necessary server information and the get_servers_settings() function gets you all the server related settings. In these functions, I have bound the access token into the header to get servers and its settings, decode the returned data from JSON and return it to the view file.

public function get_servers()
{
	try
	{
		$url = self::API_URL . "/server";
		$option = array('exceptions' => false);
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->get($url, array('headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}

public function get_servers_settings($server_id)
{
	try
	{
		$url = self::API_URL . "/server/manage/settings";
		$option = array('exceptions' => false);
		$data = ['server_id' => $server_id];
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->get($url, array('query' => $data, 'headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}

The last function of the class is set_servers_settings(). This function updates the data on Cloudways server using a custom UI.

public function set_servers_settings($serverid,$datetimezone,$displayerrors,$apc_shmsize,$executionlimit,$memorylimit,$maxinput_vars,$maxinput_time,$modxdebug,$uploadsize)
{
	try
	{
		$url = self::API_URL . "/server/manage/settings";
		$option = array('exceptions' => false);
		$data = [
					'server_id' => $serverid,
					'date_timezone' => $datetimezone,
					'display_errors' => $displayerrors,
					'apc_shm_size' => $apc_shmsize,
					'execution_limit' => $executionlimit,
					'memory_limit' => $memorylimit,
					'max_input_vars' => $maxinput_vars,
					'max_input_time' => $maxinput_time,
					'mod_xdebug' => $modxdebug,
					'upload_size' => $uploadsize
				];
		$header = array('Authorization'=>'Bearer ' . $this->accessToken);
		$response = $this->client->post($url, array('query' => $data, 'headers' => $header));
		$result = json_decode($response->getBody()->getContents());
		return $result;
	}
	catch (RequestException $e)
	{
		$response = $this->StatusCodeHandling($e);
		return $response;
	}
}

The next step is to create the front view that uses the Cloudways API to manage server settings. Create a new file index.php in the root folder. The code for the index.php is as follows:

<?php
    include 'CloudwaysAPIClient.php';
    include 'PHPTimezone.php';
    $api_key = '6wliPkukpkmttbDT3C2arOgilhvVL8';
    $email = 'm.fayyaz@cloudways.com';
    $cw_api = new CloudwaysAPIClient($email,$api_key);
    $getserver = $cw_api->get_servers();
    foreach($getserver->servers as $serverinfo){}
    $server_settings = $cw_api->get_servers_settings($serverinfo->id);
    $success = null;
    if(isset($_POST['submit']))
    {
        $server_id = $_POST['server_id'];
        $date_timezone = $_POST['date_timezone'];
        $display_errors = $_POST['display_errors'];
        $apc_shm_size = $_POST['apc_shm_size'];
        $execution_limit = $_POST['execution_limit'];
        $memory_limit = $_POST['memory_limit'];
        $max_input_vars = $_POST['max_input_vars'];
        $max_input_time = $_POST['max_input_time'];
        $mod_xdebug = $_POST['mod_xdebug'];
        $upload_size = $_POST['upload_size'];
        $error = null;
        $result = $cw_api->set_servers_settings($server_id,$date_timezone,$display_errors,$apc_shm_size,$execution_limit,$memory_limit,$max_input_vars,$max_input_time,$mod_xdebug,$upload_size);
        if($result == [])
        {
            $success["message"] = "Settings has been saved!";
        }
        else
        {
            $success["message"] = "Kindly correct the above errors.";
        }
        $Message = urlencode($success["message"]);
        header('Location:index.php?Message='.$Message);
    }
    ?>
<html>

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Server Settings</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>

<body>
  <div class="container-fluid">
    <br>
    <div class="row">
      <div class="col-md-12">
        <h2>Server Settings</h2>
        <h4>Server Name: <?php echo $serverinfo->label; ?></h4>
        <form class="form-horizontal" method="POST" action="">
          <fieldset>
            <div class="form-group">
              <label class="col-md-4 control-label" for="server_id">SERVER ID</label>
              <div class="col-md-4">
                <input id="server_id" name="server_id" type="text" placeholder="SERVER ID" value=<?php if(isset($serverinfo->id)) { echo $serverinfo->id; } ?> class="form-control input-md" readonly>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="date_timezone">DATE TIMEZONE</label>
                <div class="col-md-4">
                  <select id="date_timezone" name="date_timezone" class="form-control">
                    <?php foreach($timezones as $region => $list)
                    {
                      print '<optgroup label="' . $region . '">' . "\n";
                      foreach($list as $timezone => $name)
                      {
                        if ($timezone == $server_settings->settings->{'date.timezone'})
                        {
                          print '<option name="' . $timezone . '" value="' . $timezone . '" selected>' . $name . '</option>' . "\n";
                        }
                        else
                        {
                          print '<option name="' . $timezone . '" value="' . $timezone . '">' . $name . '</option>' . "\n";
                        }
                      }
                      print '<optgroup>' . "\n";
                    } ?>
                  </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="display_errors">DISPLAY ERRORS</label>
              <div class="col-md-4">
                <select id="display_errors" name="display_errors" class="form-control">
                  <?php
                    if ($server_settings->settings->display_errors == 'On')
                    {
                      print '<option name="On" value="On" selected>On</option>';
                      print '<option name="Off" value="Off">Off</option>';
                    }
                    elseif ($server_settings->settings->display_errors == 'Off')
                    {
                      print '<option name="On" value="On">On</option>';
                      print '<option name="Off" value="Off" selected>Off</option>';
                    }
                  ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="apc_shm_size">APC SHM SIZE</label>
              <div class="col-md-4">
                <input id="apc_shm_size" name="apc_shm_size" type="number" placeholder="APC SHM SIZE" value=<?php if(isset($server_settings->settings->{'apc.shm_size'})) { echo $server_settings->settings->{'apc.shm_size'}; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="execution_limit">EXECUTION LIMIT</label>
              <div class="col-md-4">
                <input id="execution_limit" name="execution_limit" type="number" placeholder="EXECUTION LIMIT" value=<?php if(isset($server_settings->settings->execution_limit)) { echo $server_settings->settings->execution_limit; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="memory_limit">MEMORY LIMIT</label>
              <div class="col-md-4">
                <input id="memory_limit" name="memory_limit" type="number" placeholder="EXECUTION LIMIT" value=<?php if(isset($server_settings->settings->memory_limit)) { echo $server_settings->settings->memory_limit; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="max_input_vars">MAX INPUT VARIABLES</label>
              <div class="col-md-4">
                <input id="max_input_vars" name="max_input_vars" type="number" placeholder="EXECUTION LIMIT" value=<?php if(isset($server_settings->settings->max_input_vars)) { echo $server_settings->settings->max_input_vars; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="max_input_time">MAX INPUT TIME</label>
              <div class="col-md-4">
                <input id="max_input_time" name="max_input_time" type="number" placeholder="EXECUTION LIMIT" value=<?php if(isset($server_settings->settings->max_input_time)) { echo $server_settings->settings->max_input_time; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="mod_xdebug">XDEBUG</label>
              <div class="col-md-4">
                <select id="mod_xdebug" name="mod_xdebug" class="form-control">
                  <?php
                    if ($server_settings->settings->mod_xdebug == 'enable')
                    {
                      print '<option name="enable" value="enable" selected>Enable</option>';
                      print '<option name="disable" value="disable">Disable</option>';
                    }
                    elseif ($server_settings->settings->mod_xdebug == 'disable')
                    {
                      print '<option name="enable" value="enable">Enable</option>';
                      print '<option name="disable" value="disable" selected>Disable</option>';
                    }
                  ?>
                </select>
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="upload_size">UPLOAD SIZE</label>
              <div class="col-md-4">
                <input id="upload_size" name="upload_size" type="number" placeholder="EXECUTION LIMIT" value=<?php if(isset($server_settings->settings->upload_size)) { echo $server_settings->settings->upload_size; } ?> class="form-control input-md">
              </div>
            </div>
            <div class="form-group">
              <label class="col-md-4 control-label" for="submit"></label>
              <div class="col-md-4">
                <button id="submit" name="submit" type="submit" class="btn btn-primary">Save Settings</button>
                <span class="bg-success"><?php if(isset($_GET['Message'])) { echo $_GET['Message']; } ?> </span>
              </div>
            </div>
          </fieldset>
        </form>
      </div>
    </div>
  </div>
</body>
</html>

In the code above, I first created an object of the API class and then called the related functions to get the server information and settings. I have created a form with several fields to bind the details coming from and going to these functions.

If you paid attention to the code, I included PHPTimezone.php using include ‘PHPTimezone.php’; statement. This file is used to implement default PHP timezone capabilities. This file manages the date timezone field of the server.

Create another file PHPTimezone.php in root folder and add the following code to it:

<?php
$regions = array(
    'Africa' => DateTimeZone::AFRICA,
    'America' => DateTimeZone::AMERICA,
    'Antarctica' => DateTimeZone::ANTARCTICA,
    'Aisa' => DateTimeZone::ASIA,
    'Atlantic' => DateTimeZone::ATLANTIC,
    'Europe' => DateTimeZone::EUROPE,
    'Indian' => DateTimeZone::INDIAN,
    'Pacific' => DateTimeZone::PACIFIC
);
$timezones = array();
foreach ($regions as $name => $mask)
{
    $zones = DateTimeZone::listIdentifiers($mask);
    foreach($zones as $timezone)
    {

		$time = new DateTime(NULL, new DateTimeZone($timezone));

		$ampm = $time->format('H') > 12 ? ' ('. $time->format('g:i a'). ')' : '';

		$timezones[$name][$timezone] = substr($timezone, strlen($name) + 1) . ' - ' . $time->format('H:i') . $ampm;
	}
}
?>

The code is now done. The front view will look like this when the code is executed:

Manage Server Settings

Conclusion

In this tutorial, I used Cloudways API to get and manage server settings. I used Guzzle to perform the actions, created the class to connect to the API and manage the data easily. If you have any questions or would like to suggest an improvement, please leave a comment below.

Share your opinion in the comment section. COMMENT NOW

Fayyaz Khattak

Fayyaz is a Magento Community Manager at Cloudways - A Managed Magento Hosting Platform. His objective is to learn & share about PHP & Magento Development in Community. Fayyaz is a food lover and enjoys driving. You can email him at m.fayyaz@cloudways.com

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

Get Our Newsletter
Be the first to get the latest updates and tutorials.

THERE’S MORE TO READ.