I fell into the trap of just looking at the top result on google for calling PGP or GnuPG from a PHP script. After trying them I realized they are bad examples, and so are the next few results. Calling gpg using exec or even writing the data or private key passphrase to a file introduces unnecessary risks. It allows other users on the system to run ps and see you echo the data or passphrase to gpg. If you save the data to a file first then they can see where you are putting the files and attempt to read them before you encrypt them. The gpg process should be called using the proc_open command which will allow you to run gpg without using echo on the command line or writing unencrypted data to files. It will be sending it directly to the standard input stream of gpg. This is especially important if you do not have the ability to install GnuPG PHP libraries that already use this technique.

Using proc_open the ps command can see:
gpg -e -r 'Recipient'
Using exec the ps command can see:
echo SECRET | gpg -e -r 'Recipient'

Which one would you rather have?

This code will call gpg with proc_open. It will return the gpg result or the word “error” if there has been some kind of gpg error that did not produce a result.

My gpg encryption helper code is now available for download under the BSD license from github: