3

I am using window.location.href in a php function which forces a file download without opening an additional window. The file download works and the rest of the php script executes. However, nothing that I output after the line with the javascript in the function will show up in the iframe. Is there a way to redirect the output back to the original php script?

Here is the javascript line from the php file:

echo "<script>window.location.href='download.php';</script>";

Here is the code from download.php:

<?php
session_start(); // Starts new or resumes existing session
$filename = $_SESSION['filename']; // Creates variable from session variable
header("Content-Type: text/plain"); // Output text file
header("Content-Disposition: attachment; filename=$filename"); // Output file name
readfile($filename); // Outputs the text file
?>

This is an example of something in the php file that will not output to the iframe after the line of javascript:

echo 'Test Output';

Thanks in advance,

Jay

EDIT

I replaced the line of javascript with the following and it works perfectly:

echo "<iframe id='my_iframe' style='display:none;' src='download.php'></iframe>";
jgc9876
  • 85
  • 8
  • 1
    If you redirected the page, then it will show what the new page shows not the old one. Put your echo in the download file php script and it should show. – Moussa Khalil Jun 04 '16 at 04:27
  • Thank you for the reply. That makes sense. Is there a way to redirect back to the php file that was already running? – jgc9876 Jun 04 '16 at 04:53
  • 1
    Not practical. And that way you wouldn't be actually using an iframe for download. More like one page. Check answer for better approach :) – Moussa Khalil Jun 04 '16 at 05:28

1 Answers1

1

You don't need to put the redirect inside the iframe page.

The best way I can think of atm is to use an invisible frame as mentioned in Andrew Dunn's answer to this question

Quoting from that answer:

<iframe id="my_iframe" style="display:none;"></iframe>
<script>
function Download(url) {
document.getElementById('my_iframe').src = url;
};
</script>

Have that inside your main page. url is basically the download url ("download.php" in your case). You can use a button to make the download manual. If you want it forced. Add src=url to the iframe and remove the script.

I would advice researching and using jQuery.

Community
  • 1
  • 1
Moussa Khalil
  • 635
  • 5
  • 12
  • Awesome, I replaced the javascript line with: `echo "";` and the script now downloads the file and outputs as intended. Thank you for your help. – jgc9876 Jun 04 '16 at 06:24