in my functions.php file I've added a custom action for the template_redirect hook which must force download a file stored on the server. The code of the download works fine when it is in a simple PHP file outside of Wordpress. But the feature is broken as soon as I add this code inside my template _redirect hook. Chrome says "The site cannot be reached ... ERR_INVALID_RESPONSE". There is no error 500 or other error...
Here's the download code :
<?php
$filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html';
header( "Expires: 0" );
header( "Cache-Control: no-cache, no-store, must-revalidate" );
header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );
header( "Pragma: no-cache" );
header( "Content-type: text/html" );
header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" );
header( "Content-Type: application/force-download" );
readfile( "{$filename}" );
?>
Here's the template_redirect hook :
add_action( 'template_redirect', 'my_template_redirect' );
function my_template_redirect() {
$filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html';
header( "Expires: 0" );
header( "Cache-Control: no-cache, no-store, must-revalidate" );
header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );
header( "Pragma: no-cache" );
header( "Content-type: text/html" );
header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" );
header( "Content-Type: application/force-download" );
readfile( "{$filename}" );
exit();
}
Any idea ?
EDIT
After some more tests, the problem seems to come from the specific URL from which I'm trying to run this download. In fact, my code is like this :
add_action( 'template_redirect', 'my_template_redirect' );
function my_template_redirect() {
if ( preg_match( "/\/wp-admin\/export$/", $_SERVER['REQUEST_URI'] ) ) {
$filename = $_SERVER['DOCUMENT_ROOT'] . 'path-to-my-wordpress/wp-content/uploads/export/test.html';
header( "Expires: 0" );
header( "Cache-Control: no-cache, no-store, must-revalidate" );
header( 'Cache-Control: pre-check=0, post-check=0, max-age=0', false );
header( "Pragma: no-cache" );
header( "Content-type: text/html" );
header( "Content-Disposition:attachment; filename=\"" . basename( $filename ) . "\"" );
header( "Content-Type: application/force-download" );
readfile( "{$filename}" );
exit();
}
}
The URL is /wp-admin/export and this should launch the download of the file. Without this URL condition, the code does work when I reach the base site URL (= http://mysite.dev/). But with the condition adn trying to reach http://mysite.dev/wp-admin/export, it breaks. I also tried without the wp-admin prefix, and it also breaks.
Content-type
headers, but that shouldn't break anything.