tags:

views:

147

answers:

4

I need 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

+9  A: 

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.

Sinan Ünür
A: 
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";
}
geocar
@goe It seems you chose this answer because you do not want to use `CGI.pm` or `CGI::Simple`. I do not care which answer you pick, but not using a well established module for your CGI scripts is going to cost you in the long run.
Sinan Ünür
+3  A: 

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.

Chris Huang-Leaver
+6  A: 

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;
brian d foy