I'm currently trying to download a file from my server with a PHP AJAX request. I've build it this way:
First I'm getting all files (in this example just one) and build a link:
$invoice_number_base = 'RE-2018-12-00000039-E';
//Get all generated PDF file names by tmp path and invoice number base
foreach ( glob( '/var/www/vhosts/localhost/httpdocs/wp-content/uploads/wpo_wcpdf/attachments/' . $invoice_number_base . '*.pdf' ) as $file ) { ?>
<a target="_blank" class="admin_et_pb_button"
onclick="showGenInvoice('<?php echo $file ?>')">
<?php echo basename( $file ) ?>
</a>
<?php }
This generates this link here:
<a target="_blank" class="admin_et_pb_button" onclick="showGenInvoice('/var/www/vhosts/localhost/httpdocs/wp-content/uploads/wpo_wcpdf/attachments/RE-2018-12-00000039-E.pdf')">RE-2018-12-00000039-E.pdf</a>
Now I've build my JS function to call the AJAX function when the user clicks the button:
function showGenInvoice(file) {
var data = {
'action': 'show_gen_invoice',
'file': file
};
jQuery.post(ajaxurl, data, function () {
}).fail(function () {
alert('An error occured!')
});
}
(The function has the parameter link which contains the path to each file on my server)
After this I've build the AJAX callback in WordPress:
/**
* Get generated invoice from attachments folder so the invoices which are sent by email
*/
add_action( 'wp_ajax_show_gen_invoice', array( $this, 'show_gen_invoice' ) );
public function show_gen_invoice() {
//Get file path from request
$file = $_POST['file'];
if ( is_admin() && file_exists( $file ) ) {
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/octet-stream' );
header( 'Content-Disposition: attachment; filename="' . basename( $file ) . '"' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate' );
header( 'Pragma: public' );
header( 'Content-Length: ' . filesize( $file ) );
ob_clean();
flush();
readfile( $file );
wp_die();
} else {
wp_send_json_error( null, 500 );
wp_die();
}
}
But sadly no file gets downloaded when I hit the button. No error, just nothing happens. Whats wrong here?
Notice:
The folder where the file is located is protected and can't be reached with the normal page url and /uploads/...
Update
Please checkout my solution! It's usable when you want to download something from your server from the backend with PHP.