Skip to content

Instantly share code, notes, and snippets.

@ideadude
Created September 13, 2018 15:33
Show Gist options
  • Save ideadude/09df99c4c7856cba73111b0ce2bf8442 to your computer and use it in GitHub Desktop.
Save ideadude/09df99c4c7856cba73111b0ce2bf8442 to your computer and use it in GitHub Desktop.
Checking for PMPro membership when accessing non-WP pages.
/**
* Checking for membership when accessing non-WP pages.
* This code will work with the htaccess rewrite rules shared here:
* https://www.paidmembershipspro.com/locking-non-wordpress-files-folders-paid-memberships-pro/
*/
function my_pmpro_getfile_before_readfile( $filename, $file_mimetype ) {
if(is_dir($filename)) {
$filename .= "index.html";
$mimetype = new pmpro_mimetype();
$file_mimetype = $mimetype->getType($filename);
}
if(!pmpro_hasMembershipLevel()) {
wp_redirect(wp_login_url());
exit;
}
//if file is not found, die
if(!file_exists($filename))
{
status_header( 404 );
nocache_headers();
die("File not found.");
}
//if blacklistsed file type, redirect to it instead
$basename = basename($filename);
$parts = explode('.', $basename);
$ext = strtolower($parts[count($parts)-1]);
//build blacklist and allow for filtering
$blacklist = array("inc", "php", "php3", "php4", "php5", "phps", "phtml");
$blacklist = apply_filters("pmpro_getfile_extension_blacklist", $blacklist);
//check
if(in_array($ext, $blacklist))
{
//add a noloop param to avoid infinite loops
$uri = add_query_arg("noloop", 1, $uri);
//guess scheme and add host back to uri
if(is_ssl())
$uri = "https://" . $_SERVER['HTTP_HOST'] . "/" . $uri;
else
$uri = "http://" . $_SERVER['HTTP_HOST'] . "/" . $uri;
wp_redirect($uri);
exit;
}
require_once(PMPRO_DIR . '/classes/class.mimetype.php');
//okay show the file
header("Content-type: " . $file_mimetype);
readfile($filename);
exit;
}
add_action('pmpro_getfile_before_readfile', 'my_pmpro_getfile_before_readfile', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment