How to Validate a Word Document in PHP
It’s important to validate Word DOCX document uploads before we store those files in sensitive locations.
Thankfully, we can easily validate Word documents with a few lines of ready-to- run PHP code. We’ll call a free API that checks our file for errors, warnings, and password protection policies.
To start, let’s run the below command from our command line to install the SDK with composer:
composer require cloudmersive/cloudmersive_document_convert_api_client
After that, let’s focus on authorizing our API call. We’ll need a free Cloudmersive API key for that (this will give us a limit of 800 API calls per month with no commitments).
We can then call the function using the below PHP code examples (we’ll load our file in the $input_file
variable when we make our request):
<?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\ValidateDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
try {
$result = $apiInstance->validateDocumentDocxValidation($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ValidateDocumentApi->validateDocumentDocxValidation: ', $e->getMessage(), PHP_EOL;
}
?>
That’s all there is to it — no more code required! Now we can easily ensure our Word documents are valid without writing and maintaining a lot of complex code in the process.