Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have this code which works in a file called downloads/download.php:

<?php
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile('file.pdf');
?>

It correctly prompts to download file.pdf.

I need to track downloads so I want to make use of various WP functions. To bring the page inside WP I added blog-header.php like so:

<?php
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile('file.pdf');
?>

This returns a 404. Does anyone know why bringing the page inside WP would cause this?

share|improve this question
add comment

1 Answer

up vote 2 down vote accepted

I think Wordpress is having problem with the url of your external script and throws a 404 error from the handle_404() function in the wp class in /wp-includes/class-wp.php

You can try to overcome that using for example status_header(200)

<?php
define('WP_USE_THEMES', false);
require('../wp-blog-header.php');
status_header(200);
header('Content-type: application/octet-stream');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile('file.pdf');
?>

ps:

It is informative to look at the source for the Wordpress query setup wp() that is called from the file wp-blog-header.php.

This function is defined in /wp-includes/functions.php and looks like this

function wp( $query_vars = '' ) {
    ...cut...
    $wp->main( $query_vars );
    ...cut...
}

where

 function main($query_args = '') {
    ...cut...
      $this->handle_404();
    ...cut...
}

and

 function handle_404() {
    ...cut...
    // Guess it's time to 404.
    $wp_query->set_404();
    status_header( 404 );
    nocache_headers();
    ...cut...
}

is from the wp class in /wp-includes/class-wp.php.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.