When you run your script (any script) as a cgi program under Apache, it runs under the user-id under which Apache itself runs.
That user-id may, or may not, have the same environment as when you run the script from the command-line, under (presumbaly) your own user-id.
If the environment for your own user-id includes some environment variables which need to be set to indicate to the script where to find certain things (like maybe your .fonconfig cache file(s)),