Skip to content

Instantly share code, notes, and snippets.

@joshkoenig
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshkoenig/752c948aa32b15bdbd0b to your computer and use it in GitHub Desktop.
Save joshkoenig/752c948aa32b15bdbd0b to your computer and use it in GitHub Desktop.
HOWTO: http-auth in PHP
<?php
# Here's how you can implement more nuanced logic for http auth.
# Note: this will not protect direct access to images, css, and js files.
# It will only block access to the site itself.
# It will also mean your site is not cached at the Pantheon edge at all.
#
# TODO: this will also block command-line access. To work around that
# we'd need to add an additional no-op check if the site is being accessed
# via Drush or WP-CLI.
if ($_SERVER['REMOTE_ADDR'] == 'office.ip.address') {
# This is a no-op: developers from this ip are allowed.
}
elseif (isset($_SERVER['PHP_AUTH_USER']) &&
$_SERVER['PHP_AUTH_USER'] == 'expected_user' &&
$_SERVER['PHP_AUTH_PW'] == 'expected_pass') {
# Also no-op: valid http-auth supplied!
}
else {
# No auth and no ip. Challenge the user!
header('WWW-Authenticate: Basic realm="Client Access"');
header('HTTP/1.0 401 Unauthorized');
echo 'Access to this site requires authentication.';
exit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment