goe
goe

Reputation: 5415

How can I extract just the scheme, host, and port from a URL in Perl?

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

Upvotes: 3

Views: 1416

Answers (4)

Sinan Ünür
Sinan Ünür

Reputation: 118128

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.

Upvotes: 9

brian d foy
brian d foy

Reputation: 132802

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;

Upvotes: 6

Chris Huang-Leaver
Chris Huang-Leaver

Reputation: 6089

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.

Upvotes: 3

geocar
geocar

Reputation: 9305

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";
}

Upvotes: -4

Related Questions