6

I would like to ask if it's possible to use PHP in removing a password from a password-protected PDF file in which I already know the password? I've seen this page which provides many options but using bash script. :( I was required to use PHP as much as possible. Any suggestions appreciated!

dsdeiz
  • 137
  • 2
  • 10
  • you can do it with the help of java find my answer http://stackoverflow.com/questions/29530714/how-to-open-the-secured-pdf-with-php-script/36568158#36568158 – ksh Apr 12 '16 at 08:57

2 Answers2

12

Of course it's possible, all you need to do is reverse engineer the encryption and compression and implement the reverse operations in PHP - but why bother:

<?php
   `gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=unencrypted.pdf -c .setpdfwrite -f encrypted.pdf`;
?>

C.

symcbean
  • 47,736
  • 6
  • 59
  • 94
  • Hi! Thanks for the reply. Yeah, I found this also on the link I posted above. I was getting the same error as this http://www.cyberciti.biz/faq/removing-password-from-pdf-on-linux/#comment-47555 though. – dsdeiz Jun 01 '10 at 16:17
  • 2
    If you know the password you can add `-sPDFPassword=yourpassword` to the gs command. – Simon Sobisch Dec 01 '17 at 20:26
  • you need to write it in exec with option -sPDFPassword=yourpassword as @SimonSobisch suggested – Mihir Bhatt Sep 25 '21 at 07:13
1

I use qpdf on linux to remove pdf password. To install run:

sudo apt install qpdf

Here is the function which invokes qpdf from php:

function removePdfPassword($inFilePath, $password, $outFilePath)
{
    if (empty($inFilePath) || empty($password) || !file_exists($inFilePath)) {
        return false;
    }

    $cmd = 'qpdf -password=' . escapeshellarg($password) . ' -decrypt ' . escapeshellarg($inFilePath) . ' ' . escapeshellarg($outFilePath);

    exec($cmd, $output, $retcode);
    $success = $retcode == 0;

    if (!$success) {
        @unlink($outFilePath);
    }

    return $success;
}
Dima L.
  • 3,443
  • 33
  • 30