Programming Tips - PHP: get the scheme of the current script

Date: 2017oct14 Language: php Q. PHP: get the scheme of the current script A. There is a $_SERVER['REQUEST_SCHEME'] but its not reliable so this is a way that always works
# Helper function function safeAccess(array &$myarray, string $key): string { if (!isset($myarray[$key])) return ''; return $myarray[$key]; } function getScheme(): string { $scheme = safeAccess($_SERVER, 'REQUEST_SCHEME'); $https = safeAccess($_SERVER, 'HTTPS'); $port = safeAccess($_SERVER, 'SERVER_PORT'); if ($scheme == 'https' || $https == 'on' || $port == '443') { return 'https'; } return 'http'; }