25 August 2010

Drupal staging site security

Suppose you have a Drupal staging site where you are preparing to go live or testing new features. You could install this on a separate domain that you have. Here's how to redirect casual users to your live site, while giving those in the know easy entry.

The crucial trick is to use a Session variable to indicate an authorised user. All Drupal access is via the root index.php file (except use of static files). index.php is amended to redirect users who do not have the session variable set correctly. Another secret file eg password.php, is used to let you get into the site by setting the session variable.

In the following example, www.example.com is your live domain and www.example.info is the staging server. The following code is on the staging server.

In index.php add this code after the line that contains drupal_bootstrap...

if( $_SESSION['password']!='asecret')
{
header('Location: http://www.example.com/');
exit;
}


Create a secret file in the root directory eg password.php with content like this:

<?php

require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

if( $_SESSION['password']=='asecret')
{
header('Location: http://www.example.info/');
die();
}

$pwd = trim($_POST['pwd']);
if( get_magic_quotes_gpc())
{
$pwd = stripslashes($pwd);
}
if( $pwd=='asecret')
{
$_SESSION['password'] = $pwd;
header('Location: http://www.example.info/');
die();
}
?>

<html>
<body>

<form method="post">

Security:
<input type="text" name="pwd" />
<input type="submit" value="Go" />

</form>

</body>
</html>

No comments: