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

$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 is the author of Advanced Microservices and is a prolific public speaker with a passion for reducing complex problems into simple language and diagrams. His career includes working at Fortune 50's in the Midwest, co-founding a successful startup, and everything in between.