Home » Php » php – GPG Error Code 2

php – GPG Error Code 2

Posted by: admin July 12, 2020 Leave a comment


GPG is always returning 2 at the result. My code is as follows

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile";

Where outfile is the file where the encrypted data will be written and infile is the unencrypted data.

I don’t know why this is happening. Can anyone please tell me what’s wrong. Thanks.

How to&Answers:

GPG is asking whether you want to continue on with the encryption using an unsigned key. Since no user can input Y it produces an error.

To fix this put the following switches

--yes and --always-trust


See this message: http://lists.gnupg.org/pipermail/gnupg-users/2008-January/032410.html

It appears to be a permission problem. gpg is trying to access a directory that it can’t have access to, so it fails with a fatal error. (error code 2)

You can fix that by specifying a homedir directive with a directory writable by gpg. Like this:

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile --homedir /path/to/dir";

Information from man gpg:

–homedir directory
Set the name of the home directory to directory

If this option is not used it defaults to
“~/.gnupg”. It does not make sense to
use this in a options file. This also
overrides the environment variable


You also might want to concider adding key to trusted keys list:

gpg.exe --edit-key KEY_NAME
5 (level of trust)

I’ve had some problems of --always-trust parameter not functioning properly on XP windows, this helped me solve the problem.


I had the same problem, but for the decoding command

At first and general, you can get the error message by redirecting stderr to stdout.

$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile 2>&1";

Then you can modify gpg’s parameters to suit your needs. Because I had a files encrypted with a key with pass phrase I had to add several parameters.

I started with

gpg  -o $out -d $path

But it complained, that it can not open tty, then with –no-tty it outputs some other errors and finally the command for decoding files with key with pass phrase is

gpg --batch --passphrase $pass_phrase --no-tty -o $outfile -d $path_to_encoded_file

I hope this helps someone.