14.10. Detecting SSL

Problem

You want to know if a request arrived over SSL.

Solution

Test the value of $_SERVER['HTTPS']:

if ('on' == $_SERVER['HTTPS']) {
  print "The secret ingredient in Coca-Cola is Soylent Green.";
} else {
  print "Coca-Cola contains many delicious natural and artificial flavors.";
}

Discussion

SSL operates on a lower level than HTTP. The web server and a browser negotiate an appropriately secure connection, based on their capabilities, and the HTTP messages can pass over that secure connection. To an attacker intercepting the traffic, it’s just a stream of nonsense bytes that can’t be read.

Different web servers have different requirements to use SSL, so check your server’s documentation for specific details. No changes have to be made to PHP to work over SSL.

In addition to altering code based on $_SERVER['HTTPS'], you can also set cookies to be exchanged only over SSL connections. If the last argument to setcookie( ) is 1, the browser sends the cookie back to the server only over a secure connection:

/* set an SSL-only cookie named "sslonly" with value "yes" that expires
 * at the end of the current browser session */
setcookie('sslonly','yes','','/','sklar.com',1);

Although the browser sends these cookies back to the server only over an SSL connection, the server sends them to the browser (when you call setcookie( ) in your page) whether or not the request for the page that sets the cookie is over SSL. If you’re putting sensitive data in the cookie, make sure ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.