Skip to content

Instantly share code, notes, and snippets.

Revisions

  1. jamesmorrison revised this gist Jan 5, 2018. 1 changed file with 1 addition and 3 deletions.
    4 changes: 1 addition & 3 deletions filter-wp-basic-http-authentication-environments.php
    Original file line number Diff line number Diff line change
    @@ -1,11 +1,10 @@
    <?php
    /**
    * Plugin Name: Filter WP Basic HTTP Authentication Environments
    * Plugin URI:
    * Description: Filter WP Basic HTTP Authentication Environments to use environment variables
    * Author: James Morrison
    * Version: 1.0.0
    * Author URI:
    * Author URI: https://www.jamesmorrison.me
    **/

    // Filter the environments
    @@ -42,4 +41,3 @@ function( $restricted_environments ) {

    }, 1, 1
    );

  2. jamesmorrison created this gist Jan 5, 2018.
    45 changes: 45 additions & 0 deletions filter-wp-basic-http-authentication-environments.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    <?php
    /**
    * Plugin Name: Filter WP Basic HTTP Authentication Environments
    * Plugin URI:
    * Description: Filter WP Basic HTTP Authentication Environments to use environment variables
    * Author: James Morrison
    * Version: 1.0.0
    * Author URI:
    **/

    // 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
    );