I would take it at its word: the connection is failing. You're on the right track, looking at environment variables. This is usually caused by differences in your environment when you run under CGI. It could be caused by running as a different user, or having a different PATH setting, or having some required file in the same directory that you run your command-line script from.