0

Is there a php command to determine the default port for a given url? parse_url only seems to return the port if it is explicitly specified in the url, but my function needs to return the correct port regardless.

Examples:

parse_url('http://example.com:81') //returns port 81

parse_url('http://example.com') //doesn't have a port in the return, but I must return 80

parse_url('https://example.com') //doesn't have a port in the return, but I must return 443

I could certainly create a hardcoded mapping of schemes to ports, but is there a better way?

Fabio
  • 23,183
  • 12
  • 55
  • 64
Greg
  • 12,119
  • 5
  • 32
  • 34
  • 1
    I don't think so - a hardcoded mapping looks like the only way. Given that the mapping is unlikely to change anytime soon, I'd say it's not that bad an option, though. – Pekka Jun 10 '13 at 17:11

1 Answers1

2

getservbyname does just that.

http://www.php.net/manual/en/function.getservbyname.php

Jigsaw
  • 81
  • 3
  • Just a note: the "service" name and URI scheme do not necessarily have to correspond. For most common schemes, this will work fine, but for example [`prospero`](https://www.rfc-editor.org/rfc/rfc4157.html) gives you 191, while it should be 1525 (per the RFC), which is actually called `prospero-np` as a service. – IS4 Sep 24 '22 at 10:50