Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.7.0+

Password-Protect a PDF with AES-256 Encryption

See more PDF Protection Examples

Demonstrates the simplest way to encrypt a PDF so that it needs a password to open. The passwords come from the UserPassword and OwnerPassword properties, and Protection with the encrypt operation and an empty JSON uses the defaults: AES-256, everything encrypted, every permission granted. Protection only records the security the PDF will be saved with. Nothing is encrypted until WriteFile is called.

Chilkat PHP Downloads

Chilkat2 PHP
<?php

use Chilkat2\JsonObject;
use Chilkat2\Pdf;

// This example requires the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.

// The PDF used in this example is available at two_page_memo.pdf

$pdf = new Pdf();
try {
    $pdf->LoadFile('qa_data/pdf/two_page_memo.pdf');

    // The passwords are taken from these two properties at the time Protection is called.
    // The user password opens the PDF.  The owner password opens it too, and is the one needed
    // later to change or remove the protection.
    $pdf->UserPassword = 'user-secret';
    $pdf->OwnerPassword = 'owner-secret';

    // An empty JSON asks for the defaults: AES-256, everything encrypted, every permission granted.
    $json = new JsonObject();
    $jsonOut = new JsonObject();
    $pdf->Protection('encrypt', $json, $jsonOut);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

// Nothing has been encrypted yet.  "pending" describes the security the PDF will be saved with.
echo 'algorithm: ', $jsonOut->StringOf('pending.algorithm'), "\n";
echo 'PDF version: ', $jsonOut->StringOf('pending.pdfVersion'), "\n";
echo 'password needed to open: ', ($jsonOut->BoolOf('pending.userPasswordRequired') ? 'true' : 'false'), "\n";

// Writing the file applies it.
try {
    $pdf->WriteFile('qa_output/memo_encrypted.pdf');

    // PreLoadCheck reports a file's encryption without loading it, and needs no password.
    $checker = new Pdf();
    $info = new JsonObject();
    $checker->PreLoadCheck('qa_output/memo_encrypted.pdf', $info);
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo 'encrypted: ', ($info->BoolOf('encrypted') ? 'true' : 'false'), "\n";
echo 'openPasswordRequired: ', ($info->BoolOf('openPasswordRequired') ? 'true' : 'false'), "\n";

// With the password, the PDF opens normally.
$reader = new Pdf();
$reader->UserPassword = 'user-secret';
try {
    $reader->LoadFile('qa_output/memo_encrypted.pdf');
} catch (\Chilkat2\Exception $e) {
    echo $e->getMessage(), "\n";
    exit;
}

echo 'pages: ', $reader->NumPages, "\n";

// Sample output:

// algorithm: aes-256
// PDF version: 1.7
// password needed to open: True
// encrypted: True
// openPasswordRequired: True
// pages: 2