Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jamesmorrison/27934a4b75e9d63fa865ad69c03c9417 to your computer and use it in GitHub Desktop.
Save jamesmorrison/27934a4b75e9d63fa865ad69c03c9417 to your computer and use it in GitHub Desktop.
Filter WP Basic HTTP Authentication Environments
<?php
/**
* Plugin Name: Filter WP Basic HTTP Authentication Environments
* Description: Filter WP Basic HTTP Authentication Environments to use environment variables
* Author: James Morrison
* Version: 1.0.0
* Author URI: https://www.jamesmorrison.me
**/
// Filter the environments
add_filter( 'wp_basic_auth_environments',
function( $restricted_environments ) {
// Ensure the expected server variable is available
if ( ! isset( $_SERVER['http_authentication_environments'] ) ) {
return $restricted_environments;
}
// This isn't a key => value based array; since we only have one value
// The simple way to remove this would be to recreate the array
$restricted_environments = [];
// Load credentials from the environment variable
// Expected format is comma separated (no spaces) like so:
// staging,testing,development
$environments = sanitize_text_field( $_SERVER['http_authentication_environments'] );
// Break the string to an array of individual sets of usernames and passwords
$environments_array = explode( ',', $environments );
// Loop through each environment
foreach ( $environments_array as $environment ) {
// Add the environment to the $restricted_environments array
$restricted_environments[] = esc_attr( $environment );
}
// Send back our restricted environments
return $restricted_environments;
}, 1, 1
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment