there’s a way to include a minimal WP for check only the current user, its roles (caps?) and then release/free it?

I need to count how many times a file in a particular sub-directory is downloaded and track who downloaded it.

I’m using a Php file to do it, it isn’t a WP file but I need to include WP to get the current user (if authenticated) and its roles (and maybe caps).

Looking at Integrating WordPress with Your Website I first used:

define('WP_USE_THEMES', false);
require('../wp-blog-header.php');

But then I had a problem with the downloads, returning a error 404 (file not found).

Lucky me on the footer of the same Codex article there’s this suggestion: Fixing false 404 headers on external pages including wp-blog-header.php

Following the suggestion I just used init which seem enough in my case:

require_once("../wp-config.php");
$wp->init();

Still, looking into $GLOBALS I think there’s much more done and left than I need.

I’m using readfile for the download, the file size maybe huge, the user check is done before, the ideal would be to include a minimal WP as fast as possible and release the WP resources just after the user check, before the readfile.

So, there’s a way to include a minimal WP for check only the current user, its roles (caps?) and then release/free it?

I seen also wp-load.php is used and looking/searching around found a lot of no no about including all those wp-* directly, but all the results where about including from a plugin, not my case, do I still need to worry about including directly?

1 Answer
1

The no no about loading wp-* files directly are reasonable when you are developing a WordPress plugin or theme, but if you are developing an external code that require WP (and that seems your case) than you must require that files, there is no alternatives.

Consider that including wp-blog-header.php is needed when you need to handle WordPress urls, or full WordPress frontend, but when you need WordPress features, including wp-load.php is better and faster, and no need to $wp->init();.

Also, setting SHORTINIT constant to true make the load faster, but doing so some features of WordPress are not available, and the user checking is one of them.

However, requiring few files, and calling a couple of functions you will be able to check user capabilities:

<?php
define( 'SHORTINIT', 1 );
require '../wp-load.php'; // adjust according to your paths
require ABSPATH . WPINC . '/formatting.php';
require ABSPATH . WPINC . '/capabilities.php';
require ABSPATH . WPINC . '/user.php';
require ABSPATH . WPINC . '/meta.php';
require ABSPATH . WPINC . '/post.php';
require ABSPATH . WPINC . '/pluggable.php';
wp_plugin_directory_constants();
wp_cookie_constants();

if( current_user_can( 'manage_options' ) ) { // check capability
  $GLOBALS = array(); // free some memory

  // require your file here

} else {
  header("HTTP/1.1 401 Unauthorized");
  exit;
}

Leave a Comment