Simple PHP API Script API v2

April 11, 2018 525 views
API PHP

Hi I am looking for a simple php code that can list all my droplets. This is for my website. I used to use this for v1 API and now it dose not work with v2 API. please help. here is my v1 code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Digital Ocean API Implementation</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
</head>

<body>


    &nbsp;&nbsp;&nbsp;&nbsp;

    <table width="700px">
        <tr>
            <td colspan="6">Data Center Control</td>
        </tr>
        <tr>
            <td  style="text-align:center">Server ID</td>
            <td  style="text-align:center">Server Name</td>
            <td  style="text-align:center">IP</td>
            <td  style="text-align:center">Status</td>
            <td  style="text-align:center">Creation Date</td>
            <td  style="text-align:center">Actions</td>

        </tr>

    <?php
    /* PHP script written by W. Al Maawali  
    # (c) 2014 Founder of Eagle Eye Digital Solutions
    # http://www.digi77.com
    # http://www.om77.net
    # script starts here:*/



    // Add your own client keys here
    $myClientID="xxxxxxxxxxxx"; 
    // Add your own API keys here
    $myDOApi="xxxxxxxxxxxxxxxxxxxx"; 


    // Get current time to speed 
    $loadingtime = time();

    // Get your data from the API provider
    $json = file_get_contents("https://api.digitalocean.com/v1/droplets/?client_id=$myClientID&api_key=$myDOApi");
    $data = json_decode($json);

    // Get live hosts
    $liveCounter = substr_count($json, 'status":"active');

    // Get Offline hosts
    $deadCounter = substr_count($json, 'status":"off');

    // Sum the total
    $counterSum=$liveCounter + $deadCounter; 



    foreach($data -> droplets  as $mydata)
    {
        // Set the droplet id for further actions
        $serverid=$mydata->id;
    ?>

            <tr>                    
            <td  style="text-align:center"><?php echo $mydata->id; ?></td>
            <td  style="text-align:center"><?php echo $mydata->name; ?></td>
            <td  style="text-align:center"><?php echo $mydata->ip_address; ?></td>
            <td  style="text-align:center"><?php echo $mydata->status; ?></td>
            <td  style="text-align:center"><?php echo $mydata->created_at; ?></td>
            <td class="td_title4" style="text-align:center"><?php echo "<a href=\"https://api.digitalocean.com/droplets/$serverid/reboot/?client_id=$myClientID&api_key=$myDOApi\" target=\"_blank\"><font color=\"red\">Reboot</font></a> - <a href=\"https://api.digitalocean.com/droplets/$serverid/shutdown/?client_id=$myClientID&api_key=$myDOApi\" target=\"_blank\"><font color=\"red\">Shut Down</font></a> - <a href=\"https://api.digitalocean.com/droplets/$serverid/power_on/?client_id=$myClientID&api_key=$myDOApi\" target=\"_blank\"><font color=\"red\">Power On</font></a>" ?></td>

    <?php
    }//end for       
    ?>
</tr>
<tr>
        <td colspan="2">
        Online Droplets: <?php echo  "<font color=\"green\">"  . $liveCounter . "</font>"?><br />
        Offline Droplets: <?php echo  "<font color=\"red\">"  . $deadCounter . "</font>"?><br />
        Total Droplets: <?php echo  "<font color=\"black\">"  . $counterSum . "</font>"?><br />
        <?php echo "Query Time: " . "<font color=\"green\">" . (time() - $loadingtime) . "s </font><br />\n"; ?>
        </td>


        </tr>
    </table>     

</body>
</html>
1 comment
  • I have made these changes can someone help me to make this work

    <?php
    require_once(__DIR__ . '/../config.php');
    
    $endpoint = "https://api.digitalocean.com/v2/droplets";
    $headers[] = "Content-type: application/json";
    $headers[] = "Authorization: Bearer $DO_API_TOKEN";
    
    $curl = curl_init();
    
    curl_setopt_array($curl, [
        CURLOPT_HTTPHEADER     => $headers,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_URL            => $endpoint,
    ]);
    
    $response = curl_exec($curl);
    
    echo "<pre>";
    print_r(json_decode($response, 1));
    echo "</pre>";
    
    curl_close($curl);
    
    <table class="table">
        <thead>
            <tr>
                <th  style="text-align:center">Server Name</th>
                <th  style="text-align:center">Status</th>
                <th  style="text-align:center">IP</th>
            </tr>
        </thead>
            <?php
                foreach ($data as $name => $value)  
                {
            ?>
            <tr>                    
                <td  style="text-align:center"><?php echo $value->name; ?></td>
                <td  style="text-align:center"><?php echo $value->status; ?></td>
                <td  style="text-align:center"><?php echo $value->ip_address; ?></td>
            <?php
                }//end for       
            ?>
            </tr>
        </table>
    
2 Answers
jtittle MOD April 12, 2018
Accepted Answer

@PenwellDlamini Give this a shot :)

<?php
$api                =   'https://api.digitalocean.com/v2/droplets';
$token              =   'your-token';

$options            =   [
    'http'          =>  [
        'method'    =>  'GET',
        'header'    =>  "Authorization: Bearer $token"
    ]
];

$context            =   stream_context_create( $options );

$results            =   file_get_contents( $api, false, $context );
$results            =   json_decode( $results );
?>

<table class="table">
    <thead>
        <tr>
            <th style="text-align:center">Droplet ID</th>
            <th style="text-align:center">Server Name</th>
            <th style="text-align:center">Status</th>
            <th style="text-align:center">Public IPv4</th>
            <th style="text-align:center">Private IPv4</th>
            <th style="text-align:center">Public IPv6</th>
        </tr>
    </thead>
<?php
foreach ( $results as $droplets )
{
    foreach ( $droplets as $droplet )
    {
        if ( isset( $droplet->id ) )
        {
?>
        <tr>
            <td style="text-align:center"><?php echo $droplet->id; ?></td>
            <td style="text-align:center"><?php echo $droplet->name; ?></td>
            <td style="text-align:center"><?php echo $droplet->status; ?></td>
            <td style="text-align:center"><?php echo $droplet->networks->v4[1]->ip_address; ?></td>
            <td style="text-align:center"><?php echo isset( $droplet->networks->v4[0]->ip_address ) ? $droplet->networks->v4[0]->ip_address : 'No Private IP'; ?></td>
            <td style="text-align:center"><?php echo $droplet->networks->v6[0]->ip_address; ?></td>
        </tr>
<?php
        }
    }
}
?>
    </thead>
</table>

That being said, i would definitely recommend using a library, such as :

https://github.com/toin0u/DigitalOceanV2

... or a similar library. It'll simplify this quite a bit since the library will handle the API, Token, and the method calls.

Please make sure you replace my-token for the $token variable.

What output are you seeing when trying to run the script? Are any errors presented?

Another option for you would be to use a pre-built library for the DO API rather than handling the json directly. This project provides a PHP API client you can use in your scripts.

  • I get a blank page. I am just looking for a very simple php code that can be able to display the list of droplets I have. I need to put this code on a page I have on my website without having to install things like composer etc... just a one page php code that can retrieve the droplets

Have another answer? Share your knowledge.