How to create a HTTPS login form easily?

2019-04-02 10:52发布

问题:

I'm new to web programming. I've created a simple login form (with php). Now I want to turn this one into a HTTPS (with SSL) login form. What should I do to achieve this?

回答1:

You will need to enable SSL, if it is not already enabled If you are going to run this in production, you will also need to purchase and install an SSL cert instead of a self-signed cert.

If SSL is enabled, then running your form with https instead of http as the comment above says will work

To force users to use the SSL version add something like the following to your .htaccess file

RewriteEngine On
Rewritebase /

RewriteCond %{HTTPS} off
RewriteRule ^login\.php https://yourdomain.com/login.php [L,R=301]


回答2:

Get an SSL certificate. Once you have HTTPS working on your server (work with your hosting company to get it working), you can use code similar to the following to force an HTTPS connection in PHP. .htaccess is another option, mentioned elsewhere.

<?

function current_protocol()
{
    $protocol = 'http';

    if ( array_key_exists( 'HTTPS', $_SERVER ) && $_SERVER['HTTPS'] === 'on' )
    {
        $protocol = 'https';
    }

    return $protocol;
}
//------------------------------------------------------------------------
function current_has_ssl()
{
    return current_protocol() == 'https';
}
//------------------------------------------------------------------------
function force_https()
{
    if ( current_has_ssl() == false )
    {
        header( "HTTP/1.1 301 Moved Permanently" );
        header( 'Location: https://example.com' );
        exit();
    }
}

//------------------------------------------------------------------------
// Usage:

force_https(); // at the top of a script before any output.


标签: php ssl https