Whenever someone says "it works fine from the command line but it doesn't work as CGI..." it makes me think of users' permissions. The user executing CGI scripts is oftentimes "apache" or "nobody". When you run the same script from the command line, you're logged in as a user with rights and permissions that are usually quite different from apache/nobody.
It may or may not help, but it's something to think about.
Cheers,
Brent
-- Yeah, I'm a Delt.