Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

14.11. Encrypting Email with GPG

Problem

You want to send encrypted email messages. For example, you take orders on your web site and need to send an email to your factory with order details for processing. By encrypting the email message, you prevent sensitive data such as credit card numbers from passing over the network in the clear.

Solution

Encrypt the body of the email message with GNU Privacy Guard (GPG) before sending it:

$message_body = escapeshellarg($message_body);
$gpg_path     = '/usr/local/bin/gpg';
$sender       = 'web@example.com';
$recipient    = 'ordertaker@example.com';
$home_dir     = '/home/web';
$user_env     = 'web';

$cmd = "echo $message_body | HOME=$home_dir USER=$user_env $gpg_path " .
       '--quiet --no-secmem-warning --encrypt --sign --armor ' .
       "--recipient $recipient --local-user $sender";

$message_body = `$cmd`;

mail($recipient,'Web Site Order',$message_body);

The email message can be decrypted by GPG, Pretty Good Privacy (PGP) or an email client plug-in that supports either program.

Discussion

PGP is a popular public key encryption program; GPG is an open-source program based on PGP. Because PGP in encumbered by a variety of patent and control issues, it’s often easier to use GPG.

The code in the Solution invokes /usr/local/bin/gpg to encrypt the message in $message_body. It uses the private key belonging to $sender and the public key belonging to $recipient. This means that only $recipient can decrypt the email message and when she does, she knows the message came from ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata