Reputation: 1997
How do I get the current domain name in a Perl script, i.e. the equivalent Perl code for the $_SERVER['HTTP_HOST']
PHP variable?
Upvotes: 0
Views: 1337
Reputation: 39158
The hostname alone is almost never useful, you also want the server port, in combination nicknamed netloc. Most likely you need this value to construct a URI to the script. This is already included in the frameworks, no need to do this manually. Code samples for both ways following.
In PSGI, read the "variable" HTTP_HOST
(alternatively, SERVER_NAME
and SERVER_PORT
) from the PSGI environment hash, or call the uri
method in Plack::Request.
use Plack::Request qw();
my $app = sub {
my ($env) = @_;
my $req = Plack::Request->new($env);
return [200, ['Content-Type' => 'text/plain'], [
sprintf "Host: %s\nURI: %s", $env->{HTTP_HOST}, $req->uri
]];
};
In CGI, combine the POSIX environment variables SERVER_NAME
and SERVER_PORT
, or call the url
method.
use CGI qw();
my $c = CGI->new;
print $c->header('text/plain');
print "Host: $ENV{SERVER_NAME}:$ENV{SERVER_PORT}\n";
print "URI: " . $c->url;
Upvotes: 8