Skip to content
This repository was archived by the owner on Jan 31, 2020. It is now read-only.

Commit 27fecdb

Browse files
committed
Clean-up server port detection
- Per @akrabat, the logic for detecting the port based on the combination of the Host header and SERVER_PORT values needed to be cleaned up to make it more clear what was being done. The new approach tests for the combination of SERVER_PORT and a host header in the `<domain>:<port>` format, and uses PCRE matched groups to set the host and/or port.
1 parent 43f4bce commit 27fecdb

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

src/Helper/ServerUrl.php

+14-13
Original file line numberDiff line numberDiff line change
@@ -79,22 +79,23 @@ protected function detectHost()
7979

8080
if (isset($_SERVER['HTTP_HOST']) && !empty($_SERVER['HTTP_HOST'])) {
8181
// Detect if the port is set in SERVER_PORT and included in HTTP_HOST
82-
if (isset($_SERVER['SERVER_PORT'])) {
83-
$portStr = ':' . $_SERVER['SERVER_PORT'];
84-
if (substr($_SERVER['HTTP_HOST'], 0-strlen($portStr), strlen($portStr)) == $portStr) {
85-
$this->setHost(substr($_SERVER['HTTP_HOST'], 0, 0-strlen($portStr)));
82+
if (isset($_SERVER['SERVER_PORT'])
83+
&& preg_match('/^(?P<host>.*?):(?P<port>\d+)$/', $_SERVER['HTTP_HOST'], $matches)
84+
) {
85+
// If they are the same, set the host to just the hostname
86+
// portion of the Host header.
87+
if ((int) $matches['port'] === (int) $_SERVER['SERVER_PORT']) {
88+
$this->setHost($matches['host']);
8689
return;
8790
}
8891

89-
// If the Host header contains a port, and it differs from the
90-
// SERVER_PORT, use the port from the Host header. Typically
91-
// this is a situation where port-forwarding is in use, and you
92-
// want to present a URI using the public port.
93-
if (preg_match('/^(?P<host>.*?):(?P<port>\d+)$/', $_SERVER['HTTP_HOST'], $matches)) {
94-
$this->setPort((int) $matches['port']);
95-
$this->setHost(rtrim($matches['host']));
96-
return;
97-
}
92+
// At this point, we have a SERVER_PORT that differs from the
93+
// Host header, indicating we likely have a port-forwarding
94+
// situation. As such, we'll set the host and port from the
95+
// matched values.
96+
$this->setPort((int) $matches['port']);
97+
$this->setHost($matches['host']);
98+
return;
9899
}
99100

100101
$this->setHost($_SERVER['HTTP_HOST']);

0 commit comments

Comments
 (0)