401 Unauthorized with PHP

Serhii Rohatin (MINDTREE LIMITED) 21 Reputation points
2021-10-04T19:40:05.837+00:00

Hi,
We are using your Text-Translation-API-V3-PHP-master

code:
"
$subscription_key = 'mykey';
$endpoint = 'https://api.cognitive.microsofttranslator.com';
$path = "/translate?api-version=3.0";

// Translate to German and Italian.
$params = "&to=de&to=it";

$text = "Hello, world!";

if (!function_exists('com_create_guid')) {
function com_create_guid() {
return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ),
mt_rand( 0, 0xffff ),
mt_rand( 0, 0x0fff ) | 0x4000,
mt_rand( 0, 0x3fff ) | 0x8000,
mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff )
);
}
}

function Translate ($host, $path, $key, $params, $content) {

$headers = "Content-type: application/json\r\n" .
    "Content-length: " . strlen($content) . "\r\n" .
    "Ocp-Apim-Subscription-Key: $key\r\n" .
    "X-ClientTraceId: " . com_create_guid() . "\r\n";

// NOTE: Use the key 'http' even if you are making an HTTPS request. See:
// http://php.net/manual/en/function.stream-context-create.php
$options = array (
    'http' => array (
        'header' => $headers,
        'method' => 'POST',
        'content' => $content
    )
);
$context  = stream_context_create ($options);
$result = file_get_contents ($host . $path . $params, false, $context);
return $result;

}

$requestBody = array (
array (
'Text' => $text,
),
);
$content = json_encode($requestBody);

$result = Translate ($endpoint, $path, $subscription_key, $params, $content);

// Note: We convert result, which is JSON, to and from an object so we can pretty-print it.
// We want to avoid escaping any Unicode characters that result contains. See:
// http://php.net/manual/en/function.json-encode.php
$json = json_encode(json_decode($result), JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo $json;"

what we have:

Warning: file_get_contents(https://api.cognitive.microsofttranslator.com/translate?api-version=3.0&to=de&to=it): failed to open stream: HTTP request failed! HTTP/1.1 401 Unauthorized in
line with $result = Translate ($endpoint, $path, $subscription_key, $params, $content);

null

what is wrong?
thankl you)

Azure Translator
Azure Translator
An Azure service to easily conduct machine translation with a simple REST API call.
340 questions
0 comments No comments
{count} votes

Accepted answer
  1. romungi-MSFT 42,116 Reputation points Microsoft Employee
    2021-10-05T06:13:39.637+00:00

    @Serhii Rohatin (MINDTREE LIMITED) I think the region might also be required in the header for this version. Please check this updated post on SO for a similar error.
    Please try to add the following header too and check if this works.

    'Ocp-Apim-Subscription-Region: '. $location, // LOCATION   
    

0 additional answers

Sort by: Most helpful