/** * Return the hostname from $_SERVER, validated and without port * * @return string */ private function buildHostname() { $hostname = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost'); // Remove port from HTTP_HOST generated $hostname $hostname = Utils::substrToString($hostname, ':'); // Validate the hostname $hostname = $this->validateHostname($hostname) ? $hostname : 'unknown'; return $hostname; }
/** * Constructor. */ public function __construct() { $name = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : (isset($_SERVER['SERVER_NAME']) ? $_SERVER['SERVER_NAME'] : 'localhost'); // Remove port from HTTP_HOST generated $name $name = Utils::substrToString($name, ':'); // Validate the hostname $name = preg_match(Uri::HOSTNAME_REGEX, $name) ? $name : 'unknown'; $port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80; $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; $root_path = str_replace(' ', '%20', rtrim(substr($_SERVER['PHP_SELF'], 0, strpos($_SERVER['PHP_SELF'], 'index.php')), '/')); // set the base if (isset($_SERVER['HTTPS'])) { $base = strtolower(@$_SERVER['HTTPS']) == 'on' ? 'https://' : 'http://'; } else { $base = 'http://'; } // add the sever name $base .= $name; // add the port of needed if ($port != '80' && $port != '443') { $base .= ":" . $port; } // check if userdir in the path and workaround PHP bug with PHP_SELF if (strpos($uri, '/~') !== false && strpos($_SERVER['PHP_SELF'], '/~') === false) { $root_path = substr($uri, 0, strpos($uri, '/', 1)) . $root_path; } // set hostname $address = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '::1'; // check for localhost variations if ($name == 'localhost' || $address == '::1' || $address == '127.0.0.1') { $this->host = 'localhost'; } else { $this->host = $name; } $this->base = $base; $this->root = $base . $root_path; $this->url = $base . $uri; }
public function testSubstrToString() { $this->assertEquals('en', Utils::substrToString('english', 'glish')); $this->assertEquals('english', Utils::substrToString('english', 'test')); $this->assertNotEquals('en', Utils::substrToString('english', 'lish')); }