Generating Password Protected ZIP Files using PHP

Multithreaded JavaScript has been published with O'Reilly!

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).

$password = 'pass';
$outfile = '';
$infile = 'file.txt';

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

@system("zip -P $password $outfile $infile");

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.

Tags: #php #security
Thomas Hunter II Avatar

Thomas has contributed to dozens of enterprise Node.js services and has worked for a company dedicated to securing Node.js. He has spoken at several conferences on Node.js and JavaScript and is an O'Reilly published author.