How to create a HTTPS login form easily?

2019-04-02 10:35发布

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?

标签: php ssl https
2条回答
Emotional °昔
2楼-- · 2019-04-02 11:08

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.
查看更多
可以哭但决不认输i
3楼-- · 2019-04-02 11:22

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]
查看更多
登录 后发表回答