How to Base64 Encode File Data in PHP
Base64 encoding is critical when we need to transmit file data through text-based channels.
Thankfully, we can easily Base64 encode binary/file data using a few lines of PHP code.
Specifically, we can use the PHP code examples provided below to call a free API that quickly converts binary/file data to a Base64 string.
To begin structuring our API call, let’s start by installing the client SDK. Let’s execute the below command from our command line to install via Composer:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, let’s turn our attention to API call authorization. We’ll need a free Cloudmersive API key to make up to 800 API calls per month with no commitments (this total will reset the following month once we reach our limit).
Let’s now use the below code examples to call the function:
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\EditTextApi(
new GuzzleHttp\Client(),
$config
);
$request = new \Swagger\Client\Model\Base64EncodeRequest(); // \Swagger\Client\Model\Base64EncodeRequest | Input request
try {
$result = $apiInstance->editTextBase64Encode($request);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditTextApi->editTextBase64Encode: ', $e->getMessage(), PHP_EOL;
}
?>
We can pass our binary or file data content in a string (as shown in the below JSON example):
{
"ContentToEncode": "string"
}
That’s all there is to it — no more code required! Now we can quickly and easily Base64 encode content with minimal code and consistent results.