3

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

4 Answers 4

9

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.

Sign up to request clarification or add additional context in comments.

Comments

6

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;

Comments

3

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.

Comments

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

2 Comments

@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.
Necromancing here... What was all the hate about? I think this is a great answer. Of course, all due respect to using established modules if they fit the bill, etc. and that's great advice for the newbie programmers, etc. etc. But if your needs are very simple, why burden yourself with a module that does a thousand time more? If all one needs is what the OP asked, this code fits the bill, and quite well IMHO.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.