Generating Password Protected ZIP Files using PHP

This is a method for compressing files using the ZIP compression and assigning passwords to them on demand. One requirement is that you are on a Linux server (the script executes command line options that aren’t present on a Windows PC).

<?php
$password = 'pass';
$outfile = 'download.zip';
$infile = 'file.txt';

header("Content-type: application/octet-stream");
header("Content-disposition: attachment; filename=$outfile");

@system("zip -P $password $outfile $infile");
readfile($outfile);
@unlink($outfile);
?>

You wouldn’t want to use the script as-is but would want to integrate it into a project. For example, make a directory full of files that you want to be purchased. Make that directory above the public_html root so that it can’t be entered by users and have the files downloaded directly.

The password should be generated once per invoice transaction and possibly mailed to the user. To prevent people from viewing/editing/reselling the code, a person would probably want to encrypt the PHP files using ioncube, or at the very least obfuscate (make it hard to read) the code. However, this is a good free (yet less secure) alternative.

3 Responses to Generating Password Protected ZIP Files using PHP
  1. Mark Reply

    Hi, can this be modified to zip a directory and sub directories?

    Thanks.

    • Thomas Hunter Reply

      It sure can. Just hop on PHP.net and read the documentation for recursing through directories.

  2. Benson Reply

    I get this message.

    Warning: system() has been disabled for security reasons in /home/xxx/public_html/backup/backup.php on line 40

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>