How can I extract just the scheme, host, and port from a URL in Perl?
I ne开发者_如何学编程ed to be able to extract just the scheme, host, and port from a URL.
So if my url in the browser is: http://www.example.com:80/something.pl
I need to be able to get the: http://www.example.com:80
The URI module can help you slice and dice a URI any which way you want.
If you are trying to do this from within a CGI script, you need to look at $ENV{SERVER_NAME}
and $ENV{SERVER_PORT}
.
Using the url
method of the CGI module you are using (e.g. CGI.pm or CGI::Simple) will make things more straightforward.
I let the URI module figure it out so I don't have to create new bugs:
use 5.010;
use URI;
my $url = 'http://www.example.com:80/something.pl';
my $uri = URI->new( $url );
say $uri->scheme;
say $uri->host;
say $uri->port;
With modperl, it's in the Apache2::RequestRec object, using either uri
, or unparsed_uri
.
You can't get the exact text typed into the user's browser from this, only what gets presented to the server.
The server name (virtual host) is in the Server object.
sub cgi_hostname {
my $h = $ENV{HTTP_HOST} || $ENV{SERVER_NAME} || 'localhost';
my $dp =$ENV{HTTPS} ? 443 : 80;
my $ds =$ENV{HTTPS} ? "s" : "";
my $p = $ENV{SERVER_PORT} || $dp;
$h .= ":$p" if ($h !~ /:\d+$/ && $p != $dp);
return "http$ds\://$h";
}
精彩评论