Posted on March 27, 2008 at 11:12 am

Force SSL connection using PHP

When place before all other output on your PHP script this little snipped will force you PHP page to be presented over SSLThis is very useful on things like Login forms.
 
if($_SERVER['SERVER_PORT'] != '443') {
    //Force SSL upon this page
    header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']);
}

Tags:, ,

2 Responses to “Force SSL connection using PHP”

  1. Adam on March 27th, 2008 at 4:58 pm says:

    Why not do it at the Web server using Apache’s mod_rewrite:

    RewriteEngine On
    RewriteCond %{SERVER_PORT} !443$
    RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R,L]

  2. Bradley Coudriet on March 27th, 2008 at 5:01 pm says:

    This is just a nice little snippet for users not familiar with mod_rewrite, or those who just want to have a single script go to HTTPS.

    Unlike you and I, not everyone is a mod_rewrite god ;-)

Leave a Reply