Skip to content

Instantly share code, notes, and snippets.

@dustinrue
Created March 13, 2023 00:44
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 dustinrue/343f49b182c275584f6b44705d0bf53f to your computer and use it in GitHub Desktop.
Save dustinrue/343f49b182c275584f6b44705d0bf53f to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: Block URLs
Plugin URI: https://dustinrue.com
Description: Block select domains from being accessed by WordPress. Rather than blocking all domains, this plugin allows you to block just specific domains instead.
Author: Dustin Rue
Version: 0.0.1
*/
/*
Usage: Similar to WP_ACCESSIBLE_HOSTS, define WP_BLOCKED_HOSTS with a comma separated list of domains
define( 'WP_BLOCKED_HOSTS', 'api.wordpress.org,*.themeisle.com' );
*/
function block_urls( $preempt, $parsed_args, $uri ) {
if ( ! defined( 'WP_BLOCKED_HOSTS' ) ) {
return false;
}
$check = parse_url( $uri );
if ( ! $check ) {
return false;
}
static $blocked_hosts = null;
static $wildcard_regex = array();
if ( null === $blocked_hosts ) {
$blocked_hosts = preg_split( '|,\s*|', WP_BLOCKED_HOSTS );
if ( false !== strpos( WP_BLOCKED_HOSTS, '*' ) ) {
$wildcard_regex = array();
foreach ( $blocked_hosts as $host ) {
$wildcard_regex[] = str_replace( '\*', '.+', preg_quote( $host, '/' ) );
}
$wildcard_regex = '/^(' . implode( '|', $wildcard_regex ) . ')$/i';
}
}
if ( ! empty( $wildcard_regex ) ) {
$results = preg_match( $wildcard_regex, $check['host'] );
if ($results > 0) {
error_log(sprintf("Blocking %s://%s%s", $check['scheme'], $check['host'], $check['path']));
} else {
error_log(sprintf("Allowing %s://%s%s", $check['scheme'], $check['host'], $check['path']));
}
return $results > 0;
} else {
$results = in_array( $check['host'], $blocked_hosts, true ); // Inverse logic, if it's in the array, then block it.
if ($results) {
error_log(sprintf("Blocking %s://%s%s", $check['scheme'], $check['host'], $check['path']));
} else {
error_log(sprintf("Allowing %s://%s%s", $check['scheme'], $check['host'], $check['path']));
}
return $results;
}
}
add_filter('pre_http_request', 'block_urls', 10, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment