So I have a WordPress plugin that creates a custom admin page, for example: http://localhost/wp/wp-admin/admin.php?page=download_file
This page has a button element that will call the following function on click:
function downloadFile(){
window.location.href += '&download';
}
And I have my php configured in a way that if there is a download
attribute present in the URL, it will return a file.
function download_file()
{
global $pagenow;
if ($pagenow === 'admin.php' && $_REQUEST['page'] === 'download_file&download') {
$fichero = 'file.txt';
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$fileName");
header("Content-Transfer-Encoding: binary");
header("Content-Length: " . filesize($fichero));
@readfile($fichero);
}
}
What I'm trying to understand is why the URL goes back to normal when this happens. (It stays as http://localhost/wp/wp-admin/admin.php?page=download_file, without the download
attribute). If instead of returning a file, I echo anything else, then the url will keep the download
attribute (http://localhost/wp/wp-admin/admin.php?page=download_file&download)
Does the browser react differently when a request to a url returns a file?
How can I take advantage of this behaviour to avoid changing the open page if later on I implement a condition to return a file and this condition isn't met, meaning that the url will return nothing? In this scenario, I would like the url to remain as http://localhost/wp/wp-admin/admin.php?page=download_file, without the attribute as it happens now.