jinsc2012 jinsc2012 - 1 year ago 173
PHP Question

No output to iframe after using window.location.href

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:

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,



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

echo "<html><iframe id='my_iframe' style='display:none;' src='download.php'></iframe></html>";

Answer Source

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>
function Download(url) {
document.getElementById('my_iframe').src = url;

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download