Force a webpage to be secure https

March 27, 2009 Web Development

Sometimes you need a certain page on your web site to be secure. ( https ). This bit of php code will help.   
Blogged By:

Team Louish
If you have a site that has multiple links to your "login" page, it might be tricky or time consuming to modify all the links on your site to make sure it starts with https://

With this bit of PHP code, you can add this to the top of your login page, and it will force the page to be secure. Even if someone removes the S from https, it will automatically add it back in.

<?PHP 
// FORCE HTTPS ON THIS PAGE
if(!ISSET($_REQUEST[force])){
    if(
$_SERVER['HTTPS']!='on'){
    
header("Location: https://www.yourdomain.com{$_SERVER[REQUEST_URI]}");
    exit;
    }
}
// FORCE HTTPS ON THIS PAGE
?>

The reason I have if(!ISSET($_REQUEST[force])){ in the code is because if you need to test something on your site but not have it auto-redirect to https, that code allows you to add "force" to the URL so it doesn't redirect. For example, login.php?force





 
Force a webpage to be secure https Sometimes you need a certain page on your web site to be secure. ( https ). This bit of php code will help.  

COMMENTS

16 January 2010 - 7:56:00 - Jeff

Thanks for the script!

Using
if($_SERVER['HTTPS']!='on'){
causes PHP notices in the error log. I tried adding isset and !isset but I could not get it to work.

Do you know how to stop the notices without changing the error reporting level?

Thanks.

30 January 2010 - 13:59:47 - Team Louish

I'm not sure if this will work or not, but you can try


if(@$_SERVER['HTTPS']!='on'){

If that doesn't work, you, you can turn off error reporting at the top of your php file, then turn it back on after the command. (I'm not sure if this is the best way, and I'm not even sure it will work, so if you test it and it doesn't work, please let me know so I can update the blog)


<?
error_reporting(0);
// FORCE HTTPS ON THIS PAGE 
if(!ISSET($_REQUEST[force])){ 
    if(
$_SERVER['HTTPS']!='on'){ 
    
header("Location: https://www.yourdomain.com{$_SERVER[REQUEST_URI]}"); 
    exit; 
    } 

// FORCE HTTPS ON THIS PAGE 
error_reporting(-1);
?>

Also, what file is the log being written to, I'll check mine to see if I'm getting the same error.





CATEGORIES


RECENT BLOGS


RECENT COMMENTS


SEARCH


More Louish Sites
Louish Pixel
Louish.Network
Louish Cream
Louish Kids
Hackers Underground
Extreme Sport 'Team Riders'
Follow Us
 Flickr
 Facebook
 Twitter
 YouTube
 Digg
 Vimeo
 365 Project