Force pdf download not working when include blog-header.php

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.

Read More

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?

Related posts

Leave a Reply

1 comment

  1. 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.