您可以利用add_rewrite_rule
创建新端点,如http://example.com/api/files/xyz
它处理请求并呈现来自服务器的内容。这允许您屏蔽文件的来源,但仍可以访问其内容。
add_rewrite_rule
需要您flush_rewrite_rules
但每次修改重写内容时,只需这样做一次。所以,基本上把这一条线留在测试中,但在生产过程中将其取出。
一旦确定url正在请求一个文件,并且要显示哪个文件,请快速is_readable
检查以确保file exists
您可以访问内容。
此时,您可以编写一些头来描述文件,读取内容并使用readfile
.
你可以把这个放在你的functions.php
或在plugin 无论主题如何,都允许访问。
代码注释中有描述
<?php
if ( ! class_exists( \'FileEndpoint\' ) ):
class FileEndpoint {
const ENDPOINT_QUERY_NAME = \'api/files\';
const ENDPOINT_QUERY_PARAM = \'__api_files\';
// WordPress hooks
public function init() {
add_filter( \'query_vars\', array ( $this, \'add_query_vars\' ), 0 );
add_action( \'parse_request\', array ( $this, \'sniff_requests\' ), 0 );
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
// Add public query vars
public function add_query_vars( $vars ) {
// add all the things we know we\'ll use
$vars[] = static::ENDPOINT_QUERY_PARAM;
$vars[] = \'file\';
return $vars;
}
// Add API Endpoint
public function add_endpoint() {
add_rewrite_rule( \'^\' . static::ENDPOINT_QUERY_NAME . \'/([^/]*)/?\', \'index.php?\' . static::ENDPOINT_QUERY_PARAM . \'=1&file=$matches[1]\', \'top\' );
//////////////////////////////////
flush_rewrite_rules( false ); //// <---------- REMOVE THIS WHEN DONE
//////////////////////////////////
}
// Sniff Requests
public function sniff_requests( $wp_query ) {
global $wp;
if ( isset(
$wp->query_vars[ static::ENDPOINT_QUERY_PARAM ],
$wp->query_vars[ \'file\' ] ) ) {
$this->handle_file_request(); // handle it
}
}
// Handle Requests
protected function handle_file_request() {
global $wp;
$file = $wp->query_vars[ \'file\' ];
$filepath = \'\';
switch ( $file ) {
// example.com/api/files/xyz
case \'xyz\':
$filepath = __DIR__ . \'/filename.txt\';
break;
}
if ( ! empty( $filepath ) ) {
// Make sure this is an accessible file
// If we can\'t read it throw an Error
if ( ! is_readable( $filepath ) ) {
$err = new WP_Error( "Forbidden", "Access is not allowed for this request.", 403 );
wp_die( $err->get_error_message(), $err->get_error_code() );
}
// We can read it, so let\'s render it
$this->serve_file( $filepath );
}
// Nothing happened, just give some feedback
$err = new WP_Error( "Bad Request", "Invalid Request.", 400 );
wp_die( $err->get_error_message(), $err->get_error_code() );
}
// Output the file
protected function serve_file( $filepath, $force_download = false ) {
if ( ! empty ( $filepath ) ) {
// Write some headers
header( "Cache-control: private" );
if ( $force_download ) {
// Allow a forced download
header( "Content-type: application/force-download" );
header( "Content-disposition: attachment; filename=\\"filename.txt\\"" );
}
header( "Content-transfer-encoding: binary\\n" );
header( "Content-Length: " . filesize( $filepath ) );
// render the contents of the file
readfile( $filepath );
// kill the request. Nothing else to do now.
exit;
}
// nothing happened, :(
return false;
}
}
$wpFileEndpoint = new FileEndpoint();
$wpFileEndpoint->init();
endif; // FileEndpoint