Showing posts with label Web Security. Show all posts
Showing posts with label Web Security. Show all posts

01 November 2008

Enforcing SSL Security For WebPages

Many times we need to add SSL security to few of our web pages for secure transactions.
Now initailly when i wanted to do so i tried to hard code the link by using "https://mylink.com ". But if the user typed the link as "http://mylink.com" the page still opened in non secure mode.
To overcome this problem i found a simple function that automatically detects if the page is in secure mode or not and then force it to go into secure mode.

Here is the code for ASP.NET 2.0:

protected void ForceHTTPS()
{
if(!Request.IsSecureConnection)
{
string server_name=HttpUtility.UrlEncode(Request.ServerVariables["SERVER_NAME"]);
string forceurl="https://"+ server_name + Request.FilePath;
Response.Redirect(forceurl);
}
}


and for PHP 5:

function ForceHTTPS()
{
if($_SERVER['HTTPS']!="on")
{
$forceurl="http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
header("location:$forceurl");
exit;
}
}

These can be very handy when only a few web pages need SSL.
Note: Please make sure that the server has a valid SSL certificate( need to purchase) for https:// to work other wise you will get page not found error or certificate expired error.