Updated on 2024-04-02 GMT+08:00

PHP API Example

This section uses Image Tagging as an example to describe how to call PHP APIs.

<?php

function TokenRequest() {
    $url = "https://{endpoint}/v2/{project_id}/image/tagging";
     $token = "Actual token value obtained by the user";
    $imagePath = __DIR__.'data/image-tagging.jpg';

    $data = array();
    if (stripos($imagePath, 'http://') !== false || stripos($imagePath, 'https://') !== false) {
        $data['url'] = $imagePath;
    } else {
        if($fp = fopen($imagePath,"rb", 0))
        {
            $gambar = fread($fp,filesize($imagePath));
            fclose($fp);

            $fileBase64 = chunk_split(base64_encode($gambar));
        } else {
            echo "Failed to read the image.";
            return;
        }
        $data['image'] = $fileBase64;
    }

    $curl = curl_init();
    $headers = array(
        "Content-Type:application/json",
        "X-Auth-Token:" . $token
    );

    /* Setting the request body */
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_NOBODY, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($curl);
    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);
    echo $response;
}

TokenRequest();
Table 1 Parameter description

Parameter

Description

url

API request URL, for example, https://{endpoint}/v2/{project_id}/image/tagging.

token

A token is a user's access credential, which includes user identities and permissions. When you call an API to access a cloud service, a token is required for identity authentication.

For details about how to obtain the token, see Authentication.

imagePath

Image path. An image file path or image URL is supported. The URL can be an HTTP/HTTPS or OBS URL.