How to Easily Validate File Uploads in PHP

Cloudmersive
2 min readMay 15, 2024

--

If our PHP file upload handler processes multiple unique file types, it might benefit from a file validation solution that does the same.

Using the below code, we can take advantage of a free file validation API that 1) autodetects file inputs and 2) checks that the contents of those documents are valid at depth. This will work for all major Office file formats (e.g., DOCX, XLSX, PPTX, etc.), over 100 image formats, HTML, and a few different data formats.

If we validate a (valid) PDF, for example, we’ll get an API response like the JSON example below:

{
"FileFormatExtension": ".pdf",
"DocumentIsValid": true,
"ErrorCount": 0,
"WarningCount": 0,
"ErrorsAndWarnings": null
}

Note that invalid documents will receive a “DocumentIsValid”: false response, and any errors or warnings found within those documents will be reported on in the response object.

To take advantage of this API, we’ll need a free API key to authorize our API calls. That will allow us to make up to 800 API calls per month with zero commitments.

When we have an API key ready, we can copy and paste the below code to structure our API call.

First, we need to install the PHP client with Composer:

composer require cloudmersive/cloudmersive_document_convert_api_client

Then we can call the function using the below code. We can paste our API key in the $config snippet (replacing the ‘YOUR_API_KEY’ string):

<?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->validateDocumentAutodetectValidation($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ValidateDocumentApi->validateDocumentAutodetectValidation: ', $e->getMessage(), PHP_EOL;
}
?>

We can load our files in the $input_file variable, and we’re good to go.

That’s all the code we’ll need! Now we can easily validate multiple different document types using a single low-code API solution.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.