How to Encrypt, Password-Protect a PDF Document using PHP
If your PHP application is converting files into PDF format, complementing that process with a PDF security workflow is a no-brainer. The below PHP code will make it easy to programmatically encrypt and password protect your PDF documents, allowing you to fluidly configure the user & owner password for your document along with the encryption key length (values are 128-bit RC4 encryption or 256-bit AES encryption).
To take advantage of this API, you’ll need to start by running this command to install the SDK:
composer require cloudmersive/cloudmersive_document_convert_api_client
After installation, simply include the remaining code examples and pass a free-tier API key with your request for authorization (get one by registering a free account on our website):
<?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\EditPdfApi(
new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.
$user_password = "user_password_example"; // string | Password of a user (reader) of the PDF file
$owner_password = "owner_password_example"; // string | Password of a owner (creator/editor) of the PDF file
$encryption_key_length = "encryption_key_length_example"; // string | Possible values are \"128\" (128-bit RC4 encryption) and \"256\" (256-bit AES encryption). Default is 256.
try {
$result = $apiInstance->editPdfEncrypt($input_file, $user_password, $owner_password, $encryption_key_length);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling EditPdfApi->editPdfEncrypt: ', $e->getMessage(), PHP_EOL;
}
?>
All done!