Recipe 18.13. Detecting SSL


18.13.1. Problem

You want to know if a request arrived over SSL.

18.13.2. Solution

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

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

18.13.3. 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 trUE, the browser sends the cookie back to the server only over a secure connection:

<?php /* Set an SSL-only cookie named "sslonly" with value "yes" that expires at the    end of the current browser session. */ setcookie('sslonly', 'yes', '', '/', 'example.org', true); ?> 

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 that you set the cookie only in an SSL request as well. Also, keep in mind that the cookie data is unencrypted on the user's computer.

18.13.4. See Also

Documentation on setcookie( ) at http://php.net/setcookie.




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net