Drupal 5: Redirecting the user to SSL (HTTPS) for certain forms and pages

Here is a code snippet to redirect the user back and forth from HTTP to HTTPS. This example shows how to transfer node/add forms in SSL.

Adding code to the menu hook to ensure it’s executed before anything else:

<?php
function MYMODULE_menu() {
  // set a variable to keep track if something in the page should be sent in ssl
  variable_set('MYMODULE_ssl', FALSE);
  // ...code...
  $items = array();
  // ...code...
  return $items;
}
?>

Adding code to the form_alter hook, to check if certain forms should be sent in SSL:

<?php
function MYMODULE_form_alter($form_id, &$form) {
  // ...code...
  // check if form should be sent in ssl
  if (substr($form_id, -10) == '_node_form') {
    variable_set('MYMODULE_ssl', TRUE);
  }
  // ...code...
}
?>

The guts of the code are added to a function that’s called from the theme:

<?php
function _MYMODULE_check_ssl($enableSSL = FALSE, $messages = NULL) {

  // check for ssl enabled
  $sslOn = ($_SERVER['HTTPS'] == 'on' ? TRUE : FALSE);

  // check if the page needs to be redirected
  if ($sslOn != $enableSSL) {

    // if there are drupal messages, set them to the session.
    // when the page is redirected, the messages will be returned to the theme
    if (strlen($messages)) variable_set('MYMODULE_ssl_messages', $messages);

    // create a new URL
    $newURL = 'http' . ($sslOn ? '' : 's') . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    // redirect user
    // drupal_goto?
    header("Location: $newURL");
    die;
  }

  // check if there is a message stored in the session
  $messages = variable_get('MYMODULE_ssl_messages', NULL);
  if (strlen($messages)) {

    // unset message in session
    variable_set('MYMODULE_ssl_messages', NULL);

    // return message to theme
    return $messages;
  }

}
?>

Last I added a line to the top of the page.tpl.php file in my theme:

<?php
$messages .= _MYMODULE_check_ssl( variable_get('MYMODULE_ssl', FALSE), $messages );
?>

Updated: