The solution I've found uses ident authentication with user maps.
The first thing to notice is that, although an username is provided in the script, when connecting via Apache, that user is used for peer authentication (which fails, requiring a password). However, the system user requesting access to postgresql is the one running Apache (namely www-data), thus enabling us to configure an user map, allowing is to authenticate to the server as another system user (thus leveraging ident authentication). Here follows the configuration files content:
In pg_ident.conf we configure the user map:
# MAPNAME      SYSTEM-USERNAME         PG-USERNAME
web            www-data                dbuser
web            dbuser                  dbuser
In pg_hba.conf we add the map as an option to the local peer authentication:
# "local" is for Unix domain socket connections only
# TYPE  DATABASE     USER    ADDRESS     METHOD
local   all          all                 peer map=web
After reloading the server, the script can access the database as if it was executed directly the the user "dbuser", without the need for a password.