phphttps

Redirecting from HTTP to HTTPS with PHP


I'm working on a shopping cart website and I would like to redirect the user to a HTTPS page when he's entering his billing details and maintain the HTTPS connection for the next pages until he logs out.

What do I need to install on the server (I'm using Apache) in order to do this, and how can this redirect be done from PHP?


Solution

  • Try something like this (should work for Apache and IIS):

    if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
        $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        header('HTTP/1.1 301 Moved Permanently');
        header('Location: ' . $location);
        exit;
    }