/** * Used to force a page to be accessed in via HTTPS. * Uses a standard redirect, plus will set the HSTS header * for modern browsers that support, which gives best * protection against man-in-the-middle attacks. * * @see https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security * * @param int $duration How long should the SSL header be set for? (in seconds) * Defaults to 1 year. * @param RequestInterface $request * @param ResponseInterface $response */ function force_https(int $duration = 31536000, RequestInterface $request = null, ResponseInterface $response = null) { if (is_null($request)) { $request = Services::request(null, true); } if (is_null($response)) { $response = Services::response(null, true); } if ($request->isSecure()) { return; } // If the session library is loaded, we should regenerate // the session ID for safety sake. if (class_exists('Session', false)) { Services::session(null, true)->regenerate(); } $uri = $request->uri; $uri->setScheme('https'); $uri = \CodeIgniter\HTTP\URI::createURIString($uri->getScheme(), $uri->getAuthority(true), $uri->getPath(), $uri->getQuery(), $uri->getFragment()); // Set an HSTS header $response->setHeader('Strict-Transport-Security', 'max-age=' . $duration); $response->redirect($uri); exit; }