serving the solutions day and night

Pages

Saturday, May 8, 2010

Force SSL/https using code - PHP, JAVA, .NET, C#.NET

Below the codes will explain to detect if URL is secured ssl with php, .net or java in https. If not, then code will automatically change to the secured page from http to https.

Sometimes you may need to know that the payment(secure) page is loaded via the secure connection (SSL or https). An easy way to always redirect the page to secure connection (https://) by the following below lines.

Secured connection or url always using port 443, the below code is redirect port 80 to port 443, that is secure port and also code will check the page is using https or http.

PHP Code
  if($_SERVER["HTTPS"] != "on")
  {
    $newurl = "https://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
    header("Location: $newurl");
    exit();
  }

JAVA Code
  if(!request.isSecure())
  {
    String sNewURL = "https://" + request.getServerName() + request.getRequestURI();
    if (request.getQueryString()!=null)
      sNewURL += "?"+request.getQueryString();
    response.sendRedirect(sNewURL);
  }

C#.NET Code
  if (!Request.IsSecureConnection)
  {
    String sNewURL = "https://" + Request.ServerVariables["SERVER_NAME"] + Request.ServerVariables["URL"];
    Response.Redirect(sNewURL );
  }

2 comments:

Steve Holdoway said...

...and if you're not actually running https on this website? If you're adding this deep in your code, then I think you should check for that at least!

If you're forcing it for the whole website, I'd let the web server perform this redirect... eg for apache

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

makdns said...

Hello Steve

I agree , but my code is only for the secure page not for complete project.
If it for complete project then we can go with your way. But mostly i wrote it for common all the program language

thanks
makdns.blogspot.com