How to Detect Base64 Encoding in PHP
Identifying Base64 encoding strings isn’t always intuitive, and writing code to automate Base64 detection can be quite challenging.
Thankfully, we can quickly detect if strings are Base64 encoded using a free API. We can call this API easily using ready-to-run PHP code examples provided below.
First, we’ll need to install the SDK. We can install with Composer by running the below command from our command line:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, we can 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.
Lastly, we can structure our input request like the below JSON example:
{
"Base64ContentToDetect": "string"
}
And we can pass that input through the below 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\Base64DetectRequest(); // \Swagger\Client\Model\Base64DetectRequest | Input request
try {
$result = $apiInstance->editTextBase64Detect($request);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditTextApi->editTextBase64Detect: ', $e->getMessage(), PHP_EOL;
}
?>
All done! Now we can easily identify Baset64 encoded strings and take relevant next steps with our content based on this result.